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?
If you call your event handler on markup, as you're doing now, you can't (x-browser). But if you bind the click event with jquery, it's possible the following way:
Markup:
Javascript:
Since the event ob
in IE you can get the event object by
window.event
in other browsers with no'use strict'
directive, it is possible to get byarguments.callee.caller.arguments[0]
.Write your event handler declaration like this:
Then your "myFunc()" function can access the event.
The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:
(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.
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
event
variable (and works on IE becauseevent
resolves 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
event
intomyFunc
: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
orclass
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.