How to pass event as argument to an inline event handler in JavaScript?

JavascriptEventsEvent HandlingParameter PassingInline

Javascript Problem Overview


// 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 or span.

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 and jQuery, please provide a solution for passing event to inline event hander.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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.

Solution 4 - Javascript

Here is how I would do it to prevent users from copying and pasting invalid characters into input text fields:

function validatePaste(el, e) {
  var regex = /^[a-z .'-]+$/gi;
  var key = e.clipboardData.getData('text')
  if (!regex.test(key)) {
  	e.preventDefault();
    return false;
  }
}

This function is located inside <script> tags and it is called like:

<input type="text" onpaste="validatePaste(event)">

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1643156View Question on Stackoverflow
Solution 1 - JavascriptAkram BerkawyView Answer on Stackoverflow
Solution 2 - JavascriptSemraView Answer on Stackoverflow
Solution 3 - JavascriptWadih M.View Answer on Stackoverflow
Solution 4 - JavascriptpixelView Answer on Stackoverflow