Search code examples
javascripteventsprototypejs

How do I get the element that an event handler was attached to from inside the handler?


Typically when attaching an event handler to an element, you can access the element using the .target member of the first argument passed into the handler function like so:

button.on('click', function(e) {
  alert(e.target);
});

This would return the button element.

The issue I am trying to understand is that when you have an element inside the one with the event handler, the target of the event is the inner element instead of the one that had the handler attached to it. This is an issue when my event handler needs to access data attached to the outer element.

<div class="outer" data-tag="i-need-this-data">
  <b>Click Me</b>
</div>

With this markup, attaching an event to .outer and clicking on Click Me will result in event.target being the <b> instead of the <div>. This is problematic as I must use workarounds like checking for the outer class, climbing up the DOM until I see .outer, then accessing the data that way. An example of this behavior can be seen in this JSFiddle: https://jsfiddle.net/qce23qhw/

The first example in the JSFiddle shows the undesired behavior, clicking on the inner square causes event.target to be the inner square. The second example shows an implementation of my workaround.

Is there a cleaner way to get the element that the handler was attached to from inside the handler instead of the element that was clicked?


Solution

  • Just use the element you're already using in the loop. this is also set to the current element:

    $$('.two').each(function(element) {
        element.on('click', function(e) {
            alert(this.dataset.tag);
        });
    });