简体   繁体   中英

Javascript click listener, but doesn't trigger on child element?

I'm trying to move over to using plain old Javascript (moving away from jQuery, due to speed issues). I need to trigger a click event on something, and then toggle a class on the main element. Here is what I have:

document.querySelector('.wrapper-dropdown').addEventListener("click", function(event) {
   event.target.classList.toggle("active");
});

https://jsfiddle.net/h12o073L/17/

The problem I've got, is that I ONLY want the main element to add the class - not the child! Currently if I click on one of the prices, that gets the .active class (whereas I want the .wrapper-dropdown element to have the class added)

I've got to admit - I've become very lazy with jQuery, so I'm probably missing something simple ;)

You want the .active class to only be added to the .wrapper-dropdown You can use the currentTarget this will always refers to the element where you attach the event handler.

document.querySelector('.wrapper-dropdown').addEventListener("click", function(event) {
   event.currentTarget.classList.toggle("active");
});

You can use this inside event listener function:

document.querySelector('.wrapper-dropdown').addEventListener("click", function(event) {
 this.classList.toggle("active");

});

You should use the .closest() function to select the targeted .wrapper-dropdown .

The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null .

document.querySelector('.wrapper-dropdown').addEventListener("click", function(event) {
   event.target.closest('.wrapper-dropdown').classList.toggle("active");
});

 document.querySelector('.wrapper-dropdown').addEventListener("click", function(event) { event.target.closest('.wrapper-dropdown').classList.toggle("active"); }); 
 <div id="dd-price-from" class="wrapper-dropdown" tabindex="1"> <span>Price From</span> <ul class="dropdown"> <li data-what="20"><a href="#">€20</a></li> <li data-what="50"><a href="#">€50</a></li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM