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

user1643156 picture user1643156 · May 6, 2013 · Viewed 165k times · Source
// 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.

Answer

Akram Berkawy picture Akram Berkawy · May 6, 2013

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