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?
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.
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]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With