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?
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:
That works even on non-IE browsers because they execute the code in a context that has an
eventvariable (and works on IE becauseeventresolves towindow.event). I’ve tried it in IE6+, Firefox, Chrome, Safari, and Opera. Example: http://jsbin.com/iwifu4But your best bet is to use modern event handling:
HTML:
JavaScript using jQuery (since you’re using jQuery):
…or if you really want to pass
eventintomyFunc: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
idorclassto the anchor, but again, you have other choices. If you can use where it is in the document rather than adding something artificial, great.