Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  192] [ 4]  / answers: 1 / hits: 155553  / 13 Years ago, sun, may 1, 2011, 12:00:00

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?


More From » jquery

 Answers
82

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.


[#92457] Friday, April 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
magdalena

Total Points: 364
Total Questions: 101
Total Answers: 92

Location: Namibia
Member since Mon, Nov 14, 2022
2 Years ago
;