Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove a class on click using jQuery?

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'); }); 
like image 553
angela Avatar asked Oct 22 '13 14:10

angela


People also ask

How add or remove a class in jQuery?

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.

How do I add and delete class on click?

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.

Can you remove a class with jQuery?

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.


2 Answers

Why not try something like this?

$('#menu li a').on('click', function(){     $('#menu li a.current').removeClass('current');     $(this).addClass('current'); }); 

JSFiddle

like image 132
Jamie Taylor Avatar answered Oct 22 '22 05:10

Jamie Taylor


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'); }); 
like image 32
Stanley Amos Avatar answered Oct 22 '22 06:10

Stanley Amos