Tips for transitioning between classes by utilizing addClass and removeClass functions

I have developed my own jQuery Switcher and I am looking to enhance it by removing a class when clicking on a different color option. For example, if the body tag currently has the class "blue" and someone clicks on red, I want to remove the blue class and add the red class instead.

Here is the code snippet :

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

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

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

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

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

Check out the live demo here : https://jsfiddle.net/uikithemes/p18cqa5s/

Answer №1

Initially, it is worth mentioning that the each() loop can be eliminated since you have direct access to the data-color attribute within the click handler.

Furthermore, to achieve your desired outcome, you can specify a list of classes to remove separated by spaces using removeClass before adding the new class with addClass. See below for code example:

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

Updated fiddle

However, this approach may become challenging to maintain if colors are continually added or removed. A more efficient solution would involve calling a single function to set the classes on the body element whenever an option is selected or a color is clicked. See the revised code snippet below:

$(".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(); // when the page loads

Updated fiddle

Answer №2

One way to change the color theme is by removing the current color class from the body element's className, selecting the last class using .split() and .slice() with parameter -1, then applying a new color class using .toggleClass(). Make sure to pass true as a second argument in .toggleClass() to prevent removing the class if the same color swatch is clicked consecutively.

// Theme Colors Switch
$(".colors span").each(function() {
     var data_color = $(this).attr("data-color");
     $(this).click(function() {
         $("body").removeClass(document.body.className.split(" ").slice(-1)[0])
         .toggleClass(data_color, true);
     });
});

View the example on jsfiddle here.

Answer №3

To get rid of the current classes, you can utilize the removeClass() function and then use addClass() to incorporate the new class.

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

The removeClass() function will erase all classes when used without any arguments.

A more concise version

$(".colors span").click(function(e){
  e.preventDefault();
  $("body").removeClass().addClass($(this).attr("data-color"));
})

Remember to enclose your code within the document.ready event

Answer №4

Gather all the data_color values into an array, and then when a color is clicked, remove all classes from the body that are in the array. Then add the new class as shown below.

var data_color= [];
// Theme Colors Switch
$(".colors span").each(function() {
     data_color.push($(this).attr("data-color"));
     $(this).click(function() {
         $("body").removeClass(data_color.join(' ')).addClass($(this).attr("data-color"));
     });
}); 

Check out the updated Fiddle here: https://jsfiddle.net/p18cqa5s/5/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a distinct value from the data retrieved via an ajax call

I have implemented the use of jQuery AJAX to send data to a servlet in the following manner: var dataString = 'messageid='+ msgid1+'&receivedById='+receiverid; $.ajax({ type: "POST", url: "fetchSharePage", ...

How can I add background color to WordPress mouse over text?

Hey there! I'm a beginner when it comes to WordPress and currently using version 4.2.2. I'm looking to display a mouse-over background color with text on an image. The text and images are being generated dynamically from the admin panel. Below ar ...

Executing a particular function on multiple buttons that have not been initialized yet

I am struggling to make this code work for every button and I haven't been able to find an explanation for the issue. I believe it may be a small detail that I am overlooking. $(document).ready(function() { // delete the selected row from the datab ...

What is the best way to create a shaking image animation using React Native?

I am trying to create a shaking image animation in React Native when a TouchableOpacity is pressed. So far, I have implemented an animated image with the following code: const backgroundImage = require('./components/images/baby-sleep.jpg') cla ...

Content within division on top of dark overlay WITHOUT transparency

I am currently working on an on-boarding design similar to Medium's, where text is centered within a box with a black overlay and a background image. https://i.sstatic.net/dUt0I.png However, I am facing difficulty in preventing the text inside the d ...

How can I create a basic jQuery validation that only applies to the border and background without affecting the text?

I have been on a lengthy quest to find the simplest way to implement jQuery validation - essentially changing border color and background. No frills, just the basics! Many methods I've come across seem to involve a lot of code. Take this snippet as a ...

Exploring jQuery's Array Iteration Feature

Is there a way to create Custom Lists with a User-Friendly approach? For example: var unitA = []; unitA[0] = "Unit A One"; unitA[1] = "Unit A Two"; unitA[2] = "Unit A Three"; var unitB = []; unitB[0] = "Unit B One"; unitB[1] = "Unit B Two"; unitB[2] = " ...

The form submission messages that are being received are appearing blank, even when the name field is populated with an

Hey there! I'm experiencing an issue with my form. Even though I've set the name attribute to "" for all fields, the submitted data comes back blank in my email. Here's a snippet of my code: <div class="col-lg-6 ...

Single Page Site - navigation to distinct sections with 'placeholder' pages

As part of a school project, I have been tasked with designing a website. My goal is to create a single-page website, but we are required to link to different pages like contact.html. I also want the page to smoothly scroll to the navigation section when a ...

What is causing the radio button's background color not to change after it is selected?

I've been searching and exploring various solutions, but I'm encountering some difficulties with the following scenario: There are a few restrictions: Cannot utilize Javascript or Jquery. Must be achieved using pure CSS. My objective is to chan ...

Encasing the bootstrap dropdown menu and trigger within individual parent divs for a tidier appearance

Is it possible to toggle a bootstrap dropdown when it is wrapped in another div by using attributes such as data-target or aria-labelledby? I have seen examples where data-toggle="dropdown" and class="dropdown-menu" are siblings. An example of what I am r ...

Creating dual modes (night/day) for your AngularJS application

Currently, I am in the process of developing a project with Angularjs and facing an obstacle with animations. My goal is to implement a feature in my application that allows it to display in two different modes - night mode and day mode. I have come ac ...

Accessing data attributes using jQuery and the class selector

I'm looking for a way to trigger an onClick event for an entire class of elements and access their individual data attributes within the function. Typically, I would use the following method: $(".classy").click(function(){ console.log("Replace th ...

Trouble with transferring data from a div to an input field using jQuery

Currently, I am implementing an inplace edit feature for a form. The setup consists of two divs, where one holds display elements and the other contains the input form. Upon clicking the edit button, the data shifts from the display div to the input form. ...

script to pause video using jQuery

I have a script that works perfectly, but currently it only stops an instance of a playing video if a new video is started. I want to modify the script so that ALL instances of playing videos are stopped when the function stopAllButMe(); is called. Can s ...

Exploring jquery for making a background image within a DIV smoothly shrink using animation

Hoping to get help with a div that is only showing its background image: .foo { height: 55px; width: 33px; background: url('../images/foo.png'); background-repeat: no-repeat; background-position: center; background-size: contain; ...

When the button is clicked, I would like to use JavaScript to toggle the visibility of a div, allowing it to open and

I am attempting to toggle a div using JavaScript when the open and close button is clicked. However, I have encountered an issue where the div disappears when the button is clicked, possibly due to post-back. var toggle = function () { var mydiv = d ...

jquery:Error: string literal not properly terminated

Every time I add a space between a word and click to call a function, I encounter the following error: SyntaxError: unterminated string literal [Break On This Error] $(this).SelectProjectBox(363,"ssss mypage# (line 1, col 29) HTML generated by the b ...

New feature in Bootstrap 5: Fixed navigation with smooth scroll effect

Recently, I made the switch from Bootstrap 4 to Bootstrap 5 for my template. Surprisingly, I didn't encounter this issue with Bootstrap 4. Initially, I suspected that adding a flex container inside the navbar might be causing the problem, but that doe ...

maintaining the alignment of three div elements

I am struggling to keep three divs side by side within a container, each containing an image and text below it. I had this layout working perfectly before, but now the right div falls underneath the other two when the screen size is reduced, followed by th ...