What is the secret behind the functionality of this Jquery dark mode code?

I was experimenting with creating a dark/light mode toggle using jQuery and I came up with this solution

One thing that puzzles me is when I remove the 'darkmode' class, instead of adding the 'whitemode' class, it simply adds the attribute (class) without the actual class name. Surprisingly, it still functions properly. Can anyone explain this behavior?

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="darkmode.css">
    <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>

    <script src="https://kit.fontawesome.com/aa7be85309.js" crossorigin="anonymous"></script>


    <title>Dark Mode</title>
</head>
<body class='whitemode'>

<div class="darkmode"></div>


<div class="container">
    <div class="content">
        <h1>Light / Dark mode</h1>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui non numquam excepturi corrupti vel dicta commodi veritatis eaque eius harum blanditiis voluptatem dolores itaque iure ex, molestias expedita rem velit?
    </div>

    <div class="toggle-btn" id='toggle-btn'><i class="fa-regular fa-moon"></i></div>


    <script src="main.js"></script>
</div>
    
</body>
</html>

darkmode.css

body{
    transition-duration: .3s;
}
.container{
    width: 500px;
    margin: auto;
    font-family: sans-serif;
}

.toggle-btn{
    padding: 3px 5px;
    border: 1px solid red;
    border-radius: 3px;
}

#toggle-btn{
    position: fixed;
    top: 40px;
    right: 40px;
    cursor: pointer;
}

body.whitemode{
    background-color: #fff;
    color: black;
    transition-duration: .3s;
}

body.darkmode{
    background-color: black;
    color: #ffffff;
    transition-duration: .3s;
}

.border{
    border-color: #fff;
}

main.js

$(document).ready(function(){
    $("#toggle-btn").click(function(){

        if($("body").hasClass('whitemode') ? ($("body").toggleClass('whitemode'), $("body").toggleClass("darkmode"), $("#toggle-btn").toggleClass("border")) : ($("body").toggleClass("darkmode"), $("#toggle-btn").toggleClass("border")));
    });
});

Answer №1

The function is successful due to the fact that the

background-color: #fff; color: black;
styles are set as defaults for the body element in the vendor's stylesheet.

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

From HTML to Python CGI to communication with a Serial port

I am having an issue running a Python CGI script to send data to a serial port. Whenever I try to open and set the serial port to a variable, the HTML server crashes. Below is the code snippet that receives a color (red, blue, green) from the HTML page: ...

Tips for maintaining the size of a div container

Take a look at the following code snippet: <head> <title></title> <style> .section_divs { background-color: lightblue; float: left; } #section_empty { background-color: tomato; width ...

Personalizing the text of an item in a v-select interface

Can the item-text be customized for the v-select component? I am interested in customizing each item within the v-select dropdown, similar to this example: :item-text="item.name - item.description" ...

What are some tips for getting media queries to function properly?

I need help with my homepage banner image as I am trying to make it responsive by adding media queries. The goal is for the image to adapt to 3 different sizes based on the screen being used, but currently only the medium-sized version appears. Could someo ...

Best method to run AJAX-retrieved JavaScript code without relying on jQuery

Imagine receiving a response to an AJAX data load request containing a combination of JavaScript and HTML, like this: <script>window.alert('Hello World!');</script> <p>This is a paragraph. Lorem ipsum dolor sit amet...</p> ...

Issue with Checkbox Element's Margin CSS Not Being Applied

Hello everyone, I'm feeling a bit puzzled as to why the margin in my CSS isn't applying correctly to the checkbox element. Below is an example of the code I'm using: HTML: <div class="panel"> <input id="bodytype-checkbox" ...

Tips for making a table header span multiple columns in HTML5

Could someone help me with making my HTML5 heading span across the columns in the table? I want the table to end on the far right with the vertical line appearing at the right end of the table. Any assistance would be greatly appreciated! For reference, ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

Using the flexslider to override CSS styles in an <li> element

I have implemented the flexslider by whoothemes on my responsive website to showcase tiles. However, I am facing an issue with setting a specific width for the tiles on various devices. Upon inspecting with Chrome, I see this code: <li style="width: 21 ...

Introducing a fresh input field that includes a dropdown selection feature

When a user clicks on the "+" button, a new row should be added with a dropdown and input field. I want the input field name to be the dropdown value for each row. If "Facebook" is selected in the first dropdown, it should not appear in the second dropdo ...

Using the await keyword in the useEffect() React Hook: A comprehensive guide on implementation

When using several async functions within useEffect(), I am struggling to properly include the await keyword to wait for their results // Assume func1 and func2 are defined elsewhere async function func1() {...}; async function func2() {...}; // Import f ...

Angular 14: Exploring the left datepicker panel navigation in PrimeNG

In my situation, I am trying to adjust the position of the date-picker in relation to a panel displayed within a <p-calendar> element. Due to a splitter on the right side, I need to shift the date-picker towards the left. Here is the HTML code: < ...

Ensure portrait orientation images have a restricted width to maintain their aspect ratio

On a responsive site, I have set up flexslider to showcase both landscape and portrait orientation images. The smoothHeight: true option is enabled to adjust the height according to the images. However, at the largest media query where the flexslider cont ...

Caution: Attempting to access a non-existent 'sequelize' property within a circular dependency in the module exports

Issue Nodemon server.js [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Warning: connect.session() MemoryStore is not designe ...

Sort an HTML table based on concealed data

I've encountered a challenge with my HTML table that utilizes the Bootstrap table library for sorting data by column values. While it works smoothly for float or int data types, I have a specific column dedicated to displaying times in a string format ...

Looking to add the Ajax response data into a dropdown selection?

Looking to add select options dynamically, but unsure how to retrieve response values. I am able to fetch all the values in the response, but I struggle with appending them correctly in the select option. I believe the syntax is incorrect. success: funct ...

Retrieve the initial data of the AngularJS model upon button click

Previously, I was able to retrieve the initial values of the model using this.model.changed or this.model._previousAttributes in BackboneJS. Now, I am looking to achieve the same functionality in AngularJS, where I can track all changes made to the model ...

(node:2824) UnhandledPromiseRejectionWarning: ReferenceError: The variable "role" has not been declared

I am currently in the process of getting my discord bot up and running again. The issue is that he is old, and in the previous version, this functionality worked. However, after reading other posts, I discovered that in order to make it work, I need to u ...

Is there a way to use JQuery to open a new window on the same page when a link is clicked? It seems possible based

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Show Content with Lin ...

Scan the barcode with the reading device and then input it into

I'm exploring a method to transform a return function into a tab, or vice versa. My goal is to have the user scan a barcode, which would then move them to the next text field. Finally, when they reach the last field, the form should be submitted. I&ap ...