Please see this fiddle.
I am trying to add and remove a class on li elements that are clicked. It is a menu and when one clicks on each li item I want it to gain the class and all other li items have the class removed. So only one li item has the class at a time. This is how far I have got (see fiddle). I am not sure how to make the 'about-link' start with the class current, but then it is remove when one of the other li items are clicked on?
$('#about-link').addClass('current'); $('#menu li').on('click', function() { $(this).addClass('current').siblings().removeClass('current'); });
addClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements.
jQuery toggleClass() Method Using the jQuery toggleClass() can add or remove one or more classes from the selected html elements. Incase if the selected html element already has the class, then it is removed. if an element does not have the class, then it is added.
Similarly, you can remove the classes from the elements using the jQuery removeClass() method. The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.
Why not try something like this?
$('#menu li a').on('click', function(){ $('#menu li a.current').removeClass('current'); $(this).addClass('current'); });
JSFiddle
you can try this along, it may help to give a shorter code on large function.
$('#menu li a').on('click', function(){ $('li a.current').toggleClass('current'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With