views:

101

answers:

3

If I have some event handlers registered inline with my markup (deprecated, I know) like

 span id="..." onclick="foo(p1,p2,p3)"

how can I access the "event" object in the event handler function foo? Changing the above to

 span id="..." onclick="foo(event,p1,p2,p3)"

and then using it in "foo" like

function foo(e,p1,p2,p3)
{
   if (!e) e = window.event;
}

seems to work but I don't see it documented anywhere so I am wary of using it. In other words, is the first parameter to a inline event handler always the event object if it is named as such in the onclick=... markup? Is this cross-browser so it can be safely used? And if it is not named as such (as in my first example), the parameters are treated like regular parameters and the event object is not passed?

Thoughts? Thanks

+1  A: 

You're misunderstanding your code.

The string that you put in the inline handler is a normal piece of Javascript code. It does not need to be a single function call; it can even contain multiple statements (separated by semicolons, as usual)

The code in the inline handler will be given a variable called event which refers to the event object.

When you write onclick="foo(event,p1,p2,p3)", you're making a regular function call, and passing the values of four variables named event, p1, p2, and p3 as parameters to the function.

SLaks
A: 

Take a look here. This seems to line up with your example. However, there is some mention of this not working the same way in IE, so you have to check whether the first argument (event object) is defined and if not use window.event.

Another reference here. I frequently find MDC to be helpful.

Bryan Matthews
A: 

Ok, so I ran a few tests in Firefox (3.5.8/linux) and here's what I've come up with. I was unaware of 'event' being used like in example 2, but it seems to work correctly in Firefox. However, it is NOT the case that the first variable passed to a function is always the event. 'event' seems to be registered in some global object, but I can't seem to determine which one. (It's not document, or window :P)

The line of code that you have in the foo function

if (!e) e = window.event;

is basically how you have to catch events in Internet Explorer anyway, so it will work in IE and Firefox for sure. And yes, therefore, if you are not passing a variable called 'event', as in your second example, the parameters will be treated as normal parameters, and the event object will not be passed.

Chibu