Question

I have the following code:

<div id="buttons">
    <button id="btn1">1</button>
    <button id="btn2">2</button>
</div>

I attach an event handler to the <div> to handle clicks.

When I click a button, the event is captured by the div. Is there a way to get the source of the event?

For example, if the event were on each of the the buttons then the this keyword would refer to the buttons. When it's on the <div> it refers to that.

When the click is caught by the div, is there a way to locate the source of the click? i.e. which actual button was clicked?

Thanks all

Dave

Was it helpful?

Solution

You can use the originalTarget property of the event object to find out the source of the event.

JSFiddle

HTML

<div id="buttons">
    <button id="btn1">1</button>
    <button id="btn2">2</button>
</div>

JavaScript

document.getElementById('buttons').onclick = function (evt) {
    var source = evt.srcElement || evt.originalTarget
    alert(source.id);
}

OTHER TIPS

If you use jQuery, this should help:

$("#buttons").click(function(evt){
       alert($(evt.target).attr("id"));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top