BanksySan
BanksySan

Reputation: 28540

Finding the source of a click in event bubbling

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

Upvotes: 2

Views: 5400

Answers (2)

Filipe Tagliacozzi
Filipe Tagliacozzi

Reputation: 1431

If you use jQuery, this should help:

$("#buttons").click(function(evt){
       alert($(evt.target).attr("id"));
});

Upvotes: 1

Vimal Stan
Vimal Stan

Reputation: 2005

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);
}

Upvotes: 5

Related Questions