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.
That’s not using the
eventvariable in the inline event.In this case
buttonClickis a function called from the inline event; the called function does not have magical access to theeventvariable (window.eventis an IE feature). Furthermore, in the post,buttonClickwas called with 0 arguments soewill always evaluate to undefined.In any case, compare with the following which will work as access to the special
eventvariable is done from the inline event itself and the event object is then passed off to the “real” event handler function:(I would recommend using jQuery or another library to make uniform event access easier, but that’s another story ..)
Note that
window.event||eventis a dirty little trick:In IE
window.eventwill evaluate to the event object and be be used as the result of the expression (so thatevent) is never evaluated. In non-IE browsers,window.eventwill evaluate to undefined (unless someone is doing some really bad things) and thus the result will be that of theeventvariable.Reversing this to
event||window.eventwould cause a ReferenceError in browsers (i.e. IE) that do not support the W3C localeventvariable approach.