0

I'm working with a big framework, which is entity component based. So I can't change the code of the element sending the event at all, I can only work with the receiving element.

this.id does not work, because the component ( so the event handler) is attached to a parent element of the element sending the event.

I'm working with javascript, no jquery.

I wondered if there was a way to find out inside the event handler of the receiving element: which element originally sent the event?

I tried browsing other solutions like

function doWithThisElement(event) {
event = event || window.event; // IE
var target = event.target || event.srcElement; // IE

var id = target.id;
//...

}

but it doesn't work for me.

Riccardo
  • 145
  • 9
  • I'm looking at the answers you got, but somehow I get the feeling that event.target is precisely not what you're looking for. I'm unsure what you mean by "element sending the event" though. If the user clicks a button, what is the sending element in that case, with the button being the receiving one? –  Jan 21 '17 at 16:55
  • to be specific I'm working with aframe and when an animation ends it emits the event "animationend". when this happens I want my event handler to work, but only for specific animations with a certain class. That's why I need to check which animation emitted the event. Does that make it clearer? – Riccardo Jan 21 '17 at 17:09

2 Answers2

1

You have to use event.target property in order to returns the DOM element that triggered and initiated the event.

$('div').click(function(event){
    console.log(event.target.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

Use the event.target property to know which Element triggered the event. It contains a reference to the object that dispatched the event.

Also, note that this (event.target) can be different from the element on which the event was registered in case of Capturing and bubble phase of events.

document.addEventListener('click', function(e){
    var eventTarget = e.target;
    console.log(eventTarget);
    });
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41