Reputation: 36018
Suppose I add the event handler inline,use the onclick
attribute of the element like this:
<input type="button" value="Submit" onclick='buttonClick()' />
Then this is my handler:
<script type="text/javascript">
window.buttonClick=function(e){
e=e||window.event;
alert(e.type);
return false;
}
</script>
Now I want to know how to get the event object? Since the above code will throw error:
e is undefined.
Upvotes: 3
Views: 1203
Reputation:
That's not using the event
variable in the inline event.
In this case buttonClick
is a function called from the inline event; the called function does not have magical access to the event
variable (window.event
is an IE feature). Furthermore, in the post, buttonClick
was called with 0 arguments so e
will always evaluate to undefined.
In any case, compare with the following which will work as access to the special event
variable is done from the inline event itself and the event object is then passed off to the "real" event handler function:
<input type="button" value="Submit"
onclick="buttonClick(window.event||event)" />
<script type="text/javascript">
function buttonClick(e) {
alert(e.type);
return false;
}
</script>
(I would recommend using jQuery or another library to make uniform event access easier, but that's another story ..)
Note that window.event||event
is a dirty little trick:
In IE window.event
will evaluate to the event object and be be used as the result of the expression (so that event
) is never evaluated. In non-IE browsers, window.event
will evaluate to undefined (unless someone is doing some really bad things) and thus the result will be that of the event
variable.
Reversing this to event||window.event
would cause a ReferenceError in browsers (i.e. IE) that do not support the W3C local event
variable approach.
Upvotes: 3
Reputation: 7722
Assuming your code does what I think it does.. you would simply do this:
<input type="button" value="Submit" onclick='buttonClick(window.event||event)' />
Upvotes: 0