Active / Inactive JQuery Navigation Menu

I do not know how to work with javascript, so if anyone can help me, I would be very grateful.

I have a simple list:

<ul> <li id="nav1">Menu 1</li> <li id="nav2">Menu 2</li> <li id="nav3">Menu 3</li> </ul> 

When a user clicks on a menu item, I would like to add the class "menu_active".

I could achieve this result with this code:

 <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#nav1").toggle(function () {jQuery(this).addClass("menu_active");},function () {jQuery(this).removeClass("menu_active");}); jQuery("#nav2").toggle(function () {jQuery(this).addClass("menu_active");},function () {jQuery(this).removeClass("menu_active");}); jQuery("#nav3").toggle(function () {jQuery(this).addClass("menu_active");},function () {jQuery(this).removeClass("menu_active");}); }); </script> 

The script works, but if you click on # nav1, then on # nav2, then on # nav3, all three elements will have the class "menu_active".

Is there an easy way to select only one menu item?

+4
source share
2 answers

I think this should work:

 $(function(){ var menus = $("#nav1, #nav2, #nav3"); menus.click(function(){ menus.not(this).removeClass("menu_active"); $(this).toggleClass("menu_active"); }); }); 

Here is an example.

+6
source

Yes, you can remove the menu_active class from any item that contains it before , to add it to the item with a click. Take a look:

 jQuery(".menu_active").removeClass("menu_active"); 
0
source

Source: https://habr.com/ru/post/1379919/


All Articles