Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to get the event object in an event handler function without passing it as an argument?

I have an onclick attribute on my link:

<a href="#" onclick="myFunc(1,2,3)">click</a> 

That points to this event handler in JavaScript:

function myFunc(p1,p2,p3) {     //need to refer to the current event object:     alert(evt.type);         } 

Since the event object "evt" is not passed to a parameter, is it still possible to obtain this object?

I tried window.event and $(window.event), but both are undefined.

Any idea?

like image 378
LazNiko Avatar asked May 01 '11 15:05

LazNiko


2 Answers

Since the event object "evt" is not passed from the parameter, is it still possible to obtain this object?

No, not reliably. IE and some other browsers make it available as window.event (not $(window.event)), but that's non-standard and not supported by all browsers (famously, Firefox does not).

You're better off passing the event object into the function:

<a href="#" onclick="myFunc(event, 1,2,3)">click</a> 

That works even on non-IE browsers because they execute the code in a context that has an event variable (and works on IE because event resolves to window.event). I've tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4

But your best bet is to use modern event handling:

HTML:

<a href="#">click</a> 

JavaScript using jQuery (since you're using jQuery):

$("selector_for_the_anchor").click(function(event) {     // Call `myFunc`     myFunc(1, 2, 3);      // Use `event` here at the event handler level, for instance     event.stopPropagation(); }); 

...or if you really want to pass event into myFunc:

$("selector_for_the_anchor").click(function(event) {     myFunc(event, 1, 2, 3); }); 

The selector can be anything that identifies the anchor. You have a very rich set to choose from (nearly all of CSS3, plus some). You could add an id or class to the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.

like image 193
T.J. Crowder Avatar answered Oct 05 '22 12:10

T.J. Crowder


in IE you can get the event object by window.event in other browsers with no 'use strict' directive, it is possible to get by arguments.callee.caller.arguments[0].

function myFunc(p1, p2, p3) {     var evt = window.event || arguments.callee.caller.arguments[0]; } 
like image 27
otakustay Avatar answered Oct 05 '22 13:10

otakustay