skip to Main Content

I have an event listener for an object and when I click the object it’s fine, but when I click the child, event.target returns the child. Is there a way to make it so that it only returns the object I assigned the event listener to?

This is what I have as of now:

function myFunction(event) {
    if (event.target == something) {
        console.log('test') // expected test every time I click the object something in the html
    }
}

something.addEventListener('click', myFunction)
somethingelse.addEventListener('click', myFunction)

It only logs ‘test’ in the console when I click the margin/padding outside of the child because technically the event.target is not ‘something’ and rather the child of something.

Is there any way to access the object I am adding the event listener to (something) rather than the item being clicked?

Thanks.

2

Answers


  1. You can use currentTarget property instead of target property. The target property returns the element that triggered the event, while currentTarget returns the element to which the event listener is attached.

    function myFunction(event) {
    if (event.currentTarget == something) {
        console.log('test')
    }
    }
    something.addEventListener('click', myFunction)
    somethingelse.addEventListener('click', myFunction)
    

    event.currentTarget will always be the element to which the event listener is attached (something in this case), regardless of which child element was actually clicked.

    See https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget :

    The currentTarget read-only property of the Event interface identifies the element to which the event handler has been attached.

    This will not always be the same as the element on which the event was fired, because the event may have fired on a descendant of the element with the handler, and then bubbled up to the element with the handler. The element on which the event was fired is given by Event.target.

    Login or Signup to reply.
  2. Here is the code of what you can do to achieve this.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>HTML + CSS</title>
        <link rel="stylesheet" href="styles.css" />
      </head>
      <body>
    
        <div id="something">Something
          <div id="somethingelse">Something Else</div>
        </div>
        
        <script>
          function myFunction(event) {
            event.stopPropagation();
            console.log("target: ", event.target.id, "currentTarget:", event.currentTarget.id);
    
            if (event.currentTarget.id == 'something') {
              console.log("test"); // expected test every time I click the object something in the html
            }
          }
    
          document
            .getElementById("something")
            .addEventListener("click", myFunction,true);
          document
            .getElementById("somethingelse")
            .addEventListener("click", myFunction);
        </script>
      </body>
    </html>

    You can use event.currentTarget to get the element where the eventListener is attached to.

    You’ll notice the code sample has 2 additional points :

    1. addEventListener('click', myFunction, true);
    2. event.stopPropagation()

    Explanation here:

    Event handling:

    There’re two types of event handling to determine order of processing in javascript whenever something is clicked on:

    • "bubbling" – as it’s name implies, events bubble from child to parent. This is the default mode when you use addEventListener without specifying the 3rd parameter (useCapture).
    • "capturing" – the inverse of "bubbling", events travel from parent to child. To use capturing mode, set like so in the addEventListener function, addEventListener('click', myFunction, true);

    Based on your example code above, there are 2 event listeners, one on the parent, one on the child. Clicking the child will run the function twice. Depending on what you need, you can use event.stopPropagation() to prevent the event from "bubbling upwards", or "going further down" the DOM tree.

    You can remove event.stopPropgation to see the event being trigger at both parent, and child. Check this link for more information about Bubbling and capturing

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search