Once I press the button to switch all the other buttons to dark mode, it only successfully changes them once

I created a button that switches the entire page to dark mode.
I also have some dark buttons that I want to switch to light when the dark mode button is clicked.

The issue is that while changing the page to dark mode works, the dark buttons only toggle once, and the second click does not work for the first time.

Below is the code I have written:

Thank you.

let darkBackground = document.querySelector('body');
let darkModeBtn = document.getElementById('darkModeBtn');
let btnIcon = document.getElementById('btnIcon');
let codeButton = document.getElementsByClassName('btn-dark');

darkModeBtn.addEventListener('click', function() {
    darkBackground.classList.toggle('darkbackground');
    btnIcon.classList.toggle('fa-sun');
    btnIcon.classList.toggle('fa-moon');
    for (var i = 0, len = codeButton.length; len > i; i++) {
        codeButton[i].classList.toggle('btn-light');
        codeButton[i].classList.toggle('btn-dark');

    };
});
.darkbackground {
    background-color: rgb(46, 45, 49);
    transition: .15s;
    color: white;
}

.darkmodebtn {
    font-size: 1.50rem;
    padding: 0.5rem 0.85rem;
    background-color: rgba(47, 128, 237, 1);
    outline: none;
    border: 0;
    border-radius: 20px;
    color: white;
    position: fixed;
    bottom: 18px;
    right: 18px;
}

.darkmodebtn:focus {
    outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="36545959424542445746760218031805">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">
    <title>Document</title>
</head>
<body>
    <a href="#" class="btn btn-dark">Light and Black</a>
    <a href="#" class="btn btn-dark">Light and Black</a>
    <a href="#" class="btn btn-dark">Light and Black</a>
    <button class="darkmodebtn" id="darkModeBtn"><i id="btnIcon" class="fas fa-moon"></i></button>
</body>
</html>

Answer №1

let darkBackground = document.querySelector('body');
let darkModeBtn = document.getElementById('darkModeBtn');
let btnIcon = document.getElementById('btnIcon');
let codeButton = document.getElementsByClassName('code-btn');

darkModeBtn.addEventListener('click', function() {
    darkBackground.classList.toggle('darkbackground');
    btnIcon.classList.toggle('fa-sun');
    btnIcon.classList.toggle('fa-moon');
    for (var i = 0, len = codeButton.length; len > i; i++) {
        codeButton[i].classList.toggle('btn-light');
        codeButton[i].classList.toggle('btn-dark');

    };
});
.darkbackground {
    background-color: rgb(46, 45, 49);
    transition: .15s;
    color: white;
}

.darkmodebtn {
    font-size: 1.50rem;
    padding: 0.5rem 0.85rem;
    background-color: rgba(47, 128, 237, 1);
    outline: none;
    border: 0;
    border-radius: 20px;
    color: white;
    position: fixed;
    bottom: 18px;
    right: 18px;
}

.darkmodebtn:focus {
    outline: none;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9aba6a6bdbabdbba8b989fde7fce7fa">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">
    <title>Document</title>
</head>
<body>
    <a href="#" class="btn code-btn btn-dark">Light and Black</a>
    <a href="#" class="btn code-btn btn-dark">Light and Black</a>
    <a href="#" class="btn code-btn btn-dark">Light and Black</a>
    <button class="darkmodebtn" id="darkModeBtn"><i id="btnIcon" class="fas fa-moon"></i></button>
</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

Creating a state in React may lead to an endless loop

Currently, I am working on retrieving data from a Firebase real-time database and storing it in an array named 'users'. The goal is to use this array to set the "post" state. However, there seems to be an issue with the line "setPost(users);" as ...

The Raycast function seems to be failing to detect the GlTF file in Three.js

After creating a binary gltf file in Blender and animating it with Mixamo, I am encountering an issue where it is not being detected on raycast. Despite trying numerous tutorials and solutions, I have been unable to resolve the issue. const loader = new GL ...

Flask encountering an unexpected error while sending an ajax request, despite the fact that a duplicate request from another function is functioning properly

As a novice in Python and Flask, I have found it incredibly helpful to use them for running a webapp on my Raspberry Pi. Initially, I developed the app in HTML with JavaScript handling the logic. Now that I have a "finished" app, I am looking to enhance i ...

A `div` element with a height set to 100%, preventing the content from being scrollable

I've been struggling to make my content area (height:100%) scrollable, but have had no success. Despite trying various solutions, nothing seems to work. I'm using devextreme from DevExpress, but it shouldn't affect the CSS. I've set up ...

Firefox not responding to mouse movements

I am experimenting with creating an "animation" using JavaScript's "mousemove" Check it out here This is the code I am currently using $("body").mousemove(function(e){ var wWidth = $("body").width()/2 var wHeight = $("body").height()/2 var posX; v ...

How should I fix the error message "TypeError encountered while attempting to import OrbitControls"?

Encountering error while attempting to import OrbitControls JS: import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window. ...

What is the best way to manage asynchronous functions when using Axios in Vue.js?

When I refactor code, I like to split it into three separate files for better organization. In Users.vue, I have a method called getUsers that looks like this: getUsers() { this.isLoading = true this.$store .dispatch('auth/getVal ...

Determine if the server is operational using Microsoft Edge

To verify the status of my server, I have implemented the code below: <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> function checkServerStatus() { var img = document. ...

Advice for transferring a Java variable to another JSP page with embedded JavaScript code

This is a snippet of my Java class: @RequestMapping(value = "/front", method = RequestMethod.GET) public String oneMethod(@RequestParam String name, Model model) { String str = "something"; model.addAttribute("str", str); return "jsppage"; } ...

What's the best way to implement two AJAX field validations to prevent button redirection on a website?

Can anyone provide guidance on how to implement two ajax field validations for a button to prevent clicking if the data already exists or redirecting to the same page? I am seeking assistance with this issue. Below is the ajax code snippet: function vali ...

Optimizing CSS With jQuery During Browser Resize

I am currently facing an issue with recalculating the height of the li element during window resizing or scrolling. Strangely, on page load, the height is no longer being re-calculated and set to the ul's child height. Here is the code I have written ...

The script in (Nuxt.js/Vue.js) appears to only function once, becoming inactive after switching routes or refreshing the page

I'm currently in the process of transitioning my projects website to Vue.js with Nuxt.js integrated. I have been transferring all the files from the remote server to the local "static" folder. Everything seems to be functioning properly, except for t ...

Using the ::before selector to loop through td with Sass

I've recently started using sass and I'm encountering some difficulties with the ::before syntax within a @for loop. My table row consists of six td elements. <tr> <td></td> <td></td> <td da ...

How to style 1 out of every 3 div elements using absolute positioning in CSS

Imagine a setup where there is a banner at the top, with 3 divs placed side by side underneath it. The interesting part is that when you scroll down, only the center and right div should move along. #banner { background:blue; color:white; position ...

How can you personalize the dropdown button in dx-toolbar using DevExtreme?

Currently, I am working with the DevExtreme(v20.1.4) toolbar component within Angular(v8.2.14). However, when implementing a dx-toolbar and specifying locateInMenu="always" for the toolbar items, a dropdown button featuring the dx-icon-overflow i ...

Find the HTML elements within an XDocument that need to be replaced and converted into Json format

XML contains HTML tags that need to be removed using XDocument. Is there a way to identify nodes with HTML tags and replace them throughout the entire document? Below is a sample of the XML structure: <?xml version="1.0" encoding="utf-8"?> <myFie ...

Tips for expanding an input field to span across two td elements

I am attempting to design a simple form. The issue I am encountering involves creating an input field that spans two td's in the second row of my table. Despite using the colspan="2" attribute within the td tag, the input field does not expand over tw ...

How can I retrieve the word that comes after a specific word in discord.js

Currently, I'm attempting to create a bot similar to Dad bot, but I'm struggling with implementing the "Hi __ I'm, Dad" feature. Here's the code snippet that I've put together so far: var imWords = ["i'm", "I&a ...

What is the best way to execute a JavaScript function using Python Selenium?

Is it possible to repeatedly call the MapITRFtoWgs84() function with input from a text file and save the output to another text file? I believe Selenium might be the right tool for this task. Could you provide guidance on how to achieve this? Attached is ...

Jest test is unable to find the definition of Regexp

In the process of testing a module ./main.js with ./__tests__/main-test.js, I encountered an issue. One of the functions in ./main.js utilizes new Regexp(REGEX, 'g'). Upon running jest, an error message is displayed: ReferenceError: Regexp is n ...