Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When toggling a class on a menu element. How can I make it so that class gets removed on previously toggled elements?

I have this menu with different submenu’s which are just <ul>. When clicking on a submenu the .active class will get toggled and the submenu will display. However when I click on a different submenu the desired behaviour is that the .active class will be removed from the previous submenu and applied to the new one. However what obviously happens now is that the new submenu will also get the .active class and both menu’s will be open at the same time which is not what I’m after.

What would be a simple way to make sure the .active class gets removed when I click the next menu item?

This is my current code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(".menu nav ul li > ul.subnav li").on("click", function (_event) {
  $(this).children("ul.subnav").toggleClass("active");
});

>Solution :

Remove .active from the other active elements and add it for this element.

$(".menu nav ul li > ul.subnav li").on("click", function (_event) {
  $(".menu nav ul li > ul.subnav li ul.subnav.active").removeClass("active");
  $(this).children("ul.subnav").addClass("active");
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading