jquerycssswitchers

How to switch between Class using addClass & removeClass?


I create my own Switcher jQuery, and I want to remove class when click on another color, for example : I have "blue" class on body tag and when someone click on red should remove the blue class and replace it with red class etc..

Code :

$("body").addClass("wide light blue");

// Switcher jQuery Plugin
$(".switcher-toggle").click(function() {
    $("#switcher").toggleClass("open");
});

// Theme Layout Switch
$(".layout").change(function() {
    var layout = $(".layout").val();
    $(".wrapper").css("width",layout);
});

// Theme Skins Switch
$(".skins").change(function() {
    var skin = $(".skins").val();
    $("body").toggleClass(skin);
});

// Theme Colors Switch
$(".colors span").each(function() {
     var data_color = $(this).attr("data-color");
     $(this).click(function() {
         $("body").toggleClass(data_color);
     });
});

Demo : https://jsfiddle.net/uikithemes/p18cqa5s/


Solution

  • Firstly, note that the each() loop is redundant as you can access the data-color attribute directly within the click handler.

    Secondly, to achieve what you require you can provide a space-delimited list of all the classes to be removed using removeClass before adding the new class with addClass. Try this:

    $(".colors span").click(function() {
        $("body")
            .removeClass('blue red green orange carrot violet pink gold')
            .addClass($(this).data("color"));
    });
    

    Updated fiddle

    However this may become a little difficult to maintain if colours are added or removed. A better pattern would be to call a single function to set the classes on the body element whenever an option is chosen or a colour is clicked. Try this:

    $(".skins, .layout").change(applyClasses);
    $(".colors span").click(function() {
        $(this).addClass('active').siblings().removeClass('active');
        applyClasses();
    });
    
    function applyClasses() {
        var classes = [
            $(".skins").val(),
            $(".layout").val(),
            $(".colors span.active").data('color')
        ];
    
        $('body').removeClass().addClass(classes.join(' '));
    }
    
    applyClasses(); // on load
    

    Updated fiddle