Add and remove a class on click using jQuery?
Solution 1
Why not try something like this?
$('#menu li a').on('click', function(){
$('#menu li a.current').removeClass('current');
$(this).addClass('current');
});
Solution 2
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');
});
Solution 3
The other li elements are not siblings of the a element.
$('#menu li a').on('click', function(){
$(this).addClass('current').parent().siblings().children().removeClass('current');
});
Solution 4
You can do this:-
$('#about-link').addClass('current');
$('#menu li a').on('click', function(e){
e.preventDefault();
$('#menu li a.current').removeClass('current');
$(this).addClass('current');
});
Demo: Fiddle
Solution 5
You can try this,
$(function () {
$("#btnSubmit").click(function () {
$("#btnClass").removeClass("btnDiv").addClass("btn");
});
});
you can also use switchClass() method - it allows you to animate the transition of adding and removing classes at the same time.
$(function () {
$("#btnSubmit").click(function () {
$("#btnClass").switchClass("btn", "btnReset", 1000, "easeInOutQuad");
});
});
angela
Designing and building beautiful websites for Artists and Art Organisations. Coding in HTML / CSS / JQUERY Currently learning Slim in Sinatra framework and Sass.
Updated on June 01, 2021Comments
-
angela almost 3 years
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'); });