How to pass event as argument to an inline event handler in JavaScript?
Solution 1
to pass the event
object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
Solution 2
Since inline events are executed as functions you can simply use arguments.
<p id="p" onclick="doSomething.apply(this, arguments)">
and
function doSomething(e) {
if (!e) e = window.event;
// 'e' is the event.
// 'this' is the P element
}
The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.
Solution 3
You don't need to pass this
, there already is the event
object passed by default automatically, which contains event.target
which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event
object, it's already there. Try it out. And event.target
will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event
is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent
:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething()
will see event
and event.target
as per usual!
No need to pass this
everywhere, and you can keep your function signatures free from wiring information and simplify things.
Related videos on Youtube
user1643156
Updated on June 04, 2021Comments
-
user1643156 about 3 years
// this e works document.getElementById("p").oncontextmenu = function(e) { e = e || window.event; var target = e.target || e.srcElement; console.log(target); }; // this e is undefined function doSomething(e) { e = e || window.event; var target = e.target || e.srcElement; console.log(target); }
<p id="p" onclick="doSomething(e)"> <a href="#">foo</a> <span>bar</span> </p>
There are some similar questions have been asked.
But in my code, I'm trying to get child elements who's been clicked, like
a
orspan
.So what is the correct way to pass
event
as an argument to event handler, or how to get event inside handler without passing an argument?edit
I'm aware of
addEventListener
andjQuery
, please provide a solution for passing event toinline
event hander.-
Paul S. about 11 years
-
Xotic750 about 11 yearsIs there a good reason for using inline event handlers rather than switching to addEventListener? en.wikipedia.org/wiki/Unobtrusive_JavaScript
-
Wadih M. almost 5 years@Xotic750 For me yes, no need to care about re-binding them manually everytime when dynamically loading or reloading html through ajax for example.
-
Sergey Ponomarev almost 3 yearsInline handlers are more declarative
-
-
T.J. Crowder about 11 years(And for anyone wondering: Yes, this does work on Chrome, Firefox, etc., even though some [Firefox, for instance] don't have a global
event
object. It's because the context in which the DOM0 handler is called has anevent
object, even if [on some browsers] it isn't a global.) -
user1643156 about 11 years
this
refers top
, but I'm trying to geta
orspan
-
Xotic750 about 11 yearsPassing ´event´ is the only way that I know, provided it is supported. Parsing ´this´ is of no use in this situation
-
user1643156 about 11 years@AkramBerkawy that is it. I thought I could pass
e
the same way as inele.onclick = function(e)
, but it'sevent
. Thanks. -
Adrian Moisa over 6 yearsGood tip. When people will start adopting web components
call()
andapply()
will prove essential in emulating data binding capabilities available in mainstream js frameworks. One extra trick is to do something similar toObject.assign(this.querySelector('my-btn'), this)
inside a web component and voila, data binding. You can access any method of the parent web component class from the inline eventsonclick="toggleBtnActive.call(this, true)"
. -
The-null-Pointer- over 6 years@user1643156 That's very important. the parameter must be named exactly as "event"
-
cskwg over 4 yearsAt least on IE11, this is not true, There are no default arguments.
-
Wadih M. over 4 years@cskwg It does work for IE11 as well. It works on all major browsers as this is necessary for backwards compatibility. As I mentioned in the answer, only if the javascript function is fired from an event, which is the only scenario where an event exists, there will be an object already called "event" that you can readily access inside your function without having had to pass extra wiring to your function prototype. I just did a test on my machine with IE11 for an onclick event and and the 'event' variable contained a "PointerEvent object".
-
Cyberknight about 4 yearsWadih M.'s answer is way better than this. This one is misleading (like others similar to it), making people believe that "(event)" parameter should be put into the function call, when, actually, JavaScript has the "event" parameter already and readily available inside the called function, so there is no need to declare it (it took me days to realise that it made no difference changing the variable name, because it was not really being passed). Also, the explanation given there dismisses any doubts about why JS works like that (maybe it shouldn't, but that's not on me to judge...)
-
Panu Logic almost 4 yearsThe reason the 'event' object can be used as an argument to the in-HTML inline event-handler is explained in developer.mozilla.org/en-US/docs/Web/Guide/Events/… .
-
Andrei Cleland over 2 yearsI couldn't simulate a click on a radio button, am I missing something? document.getElementById("radioOption1").click() works but this did not: document.getElementById("radioOption1").dispatchEvent(new CustomEvent("click", {'bubbles': true}))