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
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.
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 :
Here is the code of what you can do to achieve this.
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 :
addEventListener('click', myFunction, true);
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:
addEventListener
without specifying the 3rd parameter (useCapture).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