Connecting Tech Pros Worldwide Help | Site Map

Writing event handler in HTML tag vs. via scripting

  #1  
Old December 5th, 2005, 05:25 PM
VA
Guest
 
Posts: n/a
If I have

<td onMouseOver="foo(event,this,'string');">something</td>

It works fine i.e. the event handler function foo is fired with the
event parameter containing the event. I do the cross-browser thing to
handle the event parameter
var evt = (evt) ? evt : ((window.event) ? event : null);
and I am all set

But when I try to do the same thing by scripting i.e. get the TD node
via the DOM and add in the event handler like so
var td=document.getElementById('tdid')
td.onmouseover=function() {
foo(event,this,"string");
|

It works in IE, but in Firefox (1.x), I get an error in the JS console
"event is not defined".

Why is this? Any way to get consistent, cross-browser behaviour?

Thanks

  #2  
Old December 5th, 2005, 06:25 PM
Martin Honnen
Guest
 
Posts: n/a

re: Writing event handler in HTML tag vs. via scripting




VA wrote:

[color=blue]
> td.onmouseover=function() {
> foo(event,this,"string");
> |
>
> It works in IE, but in Firefox (1.x), I get an error in the JS console
> "event is not defined".[/color]

You need to have a formal parameter for the event handler function:
td.onmouseover = function (evt) {
foo(evt || event, this, "string");
};

--

Martin Honnen
http://JavaScript.FAQTs.com/
  #3  
Old December 5th, 2005, 06:35 PM
Dennis Ålund
Guest
 
Posts: n/a

re: Writing event handler in HTML tag vs. via scripting


Event is not defined because it's not within the scope where it is
referred. You must add an argument when you assign the function to
onmouseover like this:

td.onmouseover=function(event) {
foo(event,this,"string");
|

  #4  
Old December 7th, 2005, 12:47 PM
Thomas 'PointedEars' Lahn
Guest
 
Posts: n/a

re: Writing event handler in HTML tag vs. via scripting


Dennis Ålund wrote:
[color=blue]
> td.onmouseover=function(event) {
> foo(event,this,"string");
> |[/color]

This will most certainly fail in IE since the local `event'
argument with value `undefined' will override any globally
defined `event' property in the scope chain.


PointedEars
Closed Thread