Partial success with jQuery dark mode toggle feature

Setting up a dark-mode toggle feature for a project, but encountering issues with switching back to light-mode after toggling

Defined two classes to control the background and text color of the body element.

Although toggling on darkmode works smoothly, toggling it off to revert to light-mode seems to be problematic. The 'dark' class is not being removed and replaced with the 'light' class as expected.

$('.switch').click(function() { 
        if ($('body').not('dark')) {
            $('body').addClass('dark');
        } 
        else if ($('body').hasClass('dark')) {
            $('body').removeClass('dark');
            $('body').addClass('light');
        }

});
.dark {
    background-color: #000000;
    transition: .5s all ease;
    color: #ffffff;
}

.light {
    background-color: #ffffff;
    transition: .5s all ease;
    color: #000000;
}


/* ----------------------------- SLIDER -----------------------------*/

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
/*  float: right;*/
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider::before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #696969;
}

/*
input:focus + .slider {
  box-shadow: 0 0 1px #696969;
}
*/

input:checked + .slider::before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

/* Rounded sliders */
.slider.round {
  border-radius: 34px;
}

.slider.round::before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> Switch theme </p> 

<label class="switch">
   <input type="checkbox">
   <span class="slider round"></span>
</label>

Answer №1

To simplify your code, consider setting the default styles for the body to be the light styles and then toggle the dark styles on CHANGE instead of CLICK.

By using click on the switch, you may be triggering the change function twice. It's recommended to handle it like a checkbox and use change instead.

Be cautious as not('dark') won't work since dark is not a selector, causing the if statement to never work as expected.

$(document).on("change",".switch",function() { 
   $("body").toggleClass("dark");
});
body {
    background-color: #ffffff;
    transition: .5s all ease;
    color: #000000;
}

body.dark {
    background-color: #000000;
    transition: .5s all ease;
    color: #ffffff;
}

/* ----------------------------- SLIDER -----------------------------*/

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider::before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #696969;
}

input:checked + .slider::before {
  -webkit-transform: translateX(26px);
  transform: translateX(26px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round::before {
  border-radius: 50%;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p> Switch theme </p> 

<label class="switch">
   <input type="checkbox">
   <span class="slider round"></span>
</label>
</body>
</html>

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

Unable to extract div HTML code from the provided HTML code

java script code $("#category select").change(function(){ var category = $('select option:selected').html(); $.ajax({ type:"Post", url:"collectiepost.php", data:"category="+category, cache:"false", success:function(html){ ...

Having difficulty displaying data in the proper format with two-way binding

In the realm of my webpage, I have a plethora of headings, paragraphs, images, and other data at my disposal. From the backend, a dataset is provided to me that includes an array with various properties housing the desired information. The challenge lies i ...

Using Ajax in a separate JavaScript file

How can I retrieve data from an Ajax call made from a different .js file? Here is the code snippet I have been working with: function ajax(url, success, error) { success += "(data)"; error += "(xhr, ajaxOptions, thrownError)"; console.log("St ...

Ensuring Contact Form Accuracy with Jquery Validation

I am trying to implement form validation using jQuery. Here is the code I am using: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2 /jquery.min.js"></script> <script type="text/javascript" src=" http:// ...

The typeface displayed is Rubik Light Font instead of the regular Rubik font

I am currently working on incorporating the Rubik Font into my project: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> < ...

Looking for assistance in arranging 3 divs next to each other

I'm looking to align three divs side by side, but I can't seem to get them to line up correctly. I've tried using simple CSS, but it's not working as expected. Any help would be greatly appreciated. Additionally, I want these divs to a ...

The class "slick" in <col class="slick"> does not add any styling or effects

My interpretation of the col element is that it can be used to assign a class to all elements in a column of a table. However, I am experiencing difficulties with this approach. While I am able to apply the class to individual td elements, I am looking for ...

Discover the precise number of columns and rows that make up a circle

Is there a way to display a popup message when clicking on a circle in the array to see the number of rows and columns that circle is from the starting point (1,1)? I'm looking for assistance with implementing this feature. var c = document.getEleme ...

"Showcase a Pair of Images with Just a Single Click. Leveraging PHP and

With two div boxes, one for Input and the other for Output as displayed below: https://i.sstatic.net/C8dhm.png My goal is to upload an image using PHP and store it in both the Input and Output folders. Upon clicking the Submit button, I want the image f ...

Issues encountered when using Vue Transition in conjunction with v-autocomplete

Attempting to conditionally display or hide a selection text field using Vue's Transition feature, but experiencing an issue where the text field appears and disappears without any transition effect. <template> <Transition v-if="is ...

Firebug detected an error with the regular expression flag "h" after executing the YUI Compressor

When I run YUI Compressor, an error occurs with the message: invalid regular expression flag h [Break On This Error] ction(event){$(this).removeClass('lumi...cs_glb.php</b> on line <b>221</b><br/> The issue seems to be with t ...

Issues with the performance of the Responsive Image Slider

Having trouble with the carousel on my website. The Navigation Bar is working, but the image slider isn't showing up despite trying multiple approaches. Bootstrap is properly linked and I've read through the documentation for the Bootstrap Carous ...

"Displaying mongoose date in the HTML5 input type date format (dd/mm/yyyy) is a simple process that can

I have a structured data in MongoDB as shown below: var Person = new Schema({ "Name": { type: String, required: true }, "DOB": { type: Date, "default": Date.now } }); An instance of this schema is created using NodeJs with mongoose ODM: { "N ...

Ways to select the initial 10 rows, final 3 rows, and middle 2 rows using Javascript

As a newcomer to Javascript, I have a couple of questions: 1) How can I retrieve the first 10 rows, the last 3 rows, and the 2 rows in the center using the code var firstTable = $('#aaa table').eq(0); 2) Is there a way to create and assign new ...

How to print a specific div from an HTML page with custom dimensions

I am looking for a solution to print just a specific div from a website with dimensions of 3"x5". Despite setting up the print button, the entire page continues to print every time. Is there a way to hide all non-div content in print preview? CSS .wholeb ...

Navigating Google GeoChart Tooltips using Google Spreadsheet Data

My objective is to create a custom GeoChart for the company's website that will display data specific to each state in the US region based on team member assignments. The GeoChart should color states according to which team member helps that state&apo ...

JavaScript regular expression to switch menu

Could someone clarify the meaning of this code snippet: /expanded/.test(classes) I understand that the '/' characters indicate a regular expression and 'expanded' is a class name. However, I am unsure about what .test(classes) does ...

What is the best way to adjust the dimensions of an element so that it only fills the size of the initial window or

I need help keeping a specific element at the initial 100% height of the viewport, without it resizing when the user changes their window size. Should I use JavaScript to determine the initial viewport height and then pass those dimensions to the CSS? Can ...

Develop a jQuery Countdown Timer that resets at regular intervals

Looking to implement a jQuery Countdown Timer that displays a countdown to a specified time, then loops back to counting down one hour before starting the next cycle of 23 hours. I have quizzes scheduled on specific dates - each quiz will be open for one ...

Modifying ID styling using JavaScript on Internet Explorer

I need to change the CSS display property from none to block using JavaScript, but only for Internet Explorer. My current code is not working for the ID #backfill-image. <script> function checkForIE() { var userAgent = navigator.userAgent; ...