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
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
Share Improve this question edited Jul 28, 2017 at 18:05 BanksySan asked Apr 24, 2013 at 14:00 BanksySanBanksySan 28.6k36 gold badges125 silver badges230 bronze badges 1- Duplicate: stackoverflow./questions/485453/… – Vimal Stan Commented Apr 24, 2013 at 14:08
2 Answers
Reset to default 5You 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);
}
If you use jQuery, this should help:
$("#buttons").click(function(evt){
alert($(evt.target).attr("id"));
});