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


// this e works
document.getElementById("p").oncontextmenu = function(e) {
    e = e || window.event;
    var target = || e.srcElement;

// this e is undefined
function doSomething(e) {
    e = e || window.event;
    var target = || e.srcElement;
<p id="p" onclick="doSomething(e)">
    <a href="#">foo</a>

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?


I'm aware of addEventListener and jQuery, please provide a solution for passing event to inline event hander.

This question is tagged with javascript events event-handling parameter-passing inline

~ Asked on 2013-05-06 17:52:36

The Best Answer is


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.srcElement;

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.

~ Answered on 2013-05-06 17:57:31


Since inline events are executed as functions you can simply use arguments.

<p id="p" onclick="doSomething.apply(this, arguments)">


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.

~ Answered on 2015-01-25 17:10:43

Most Viewed Questions: