What is the reason that JavaScript does not function properly in dark mode?

I would like the dark mode button to switch to CSS when clicked, so that in waiting mode the button appears dark and in dark mode the button is light!

var toggleButton = document.getElementById('mode-toggle')
var isDarkMode = false;

function myFunction() {
  isDarkMode = !isDarkMode;
  document.querySelectorAll('div.scrollseite,div.scrollseite2').forEach(e => e.classList.toggle('dark-mode'))
  document.querySelectorAll('div.btndarkmode').forEach(e => e.classList.toggle('btnwhitemode'))
  toggleButton.innerHTML = isDarkMode ? 'Light mode' : 'Dark mode'
}
.btndarkmode {
  background-color: #36393F;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btndarkmode:hover {
  background-color: #32353B;
  color: gray;
}

.btnwhitemode {
  background-color: white;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btnwhitemode:hover {
  background-color: white;
  color: gray;
}

.dark-mode {
  background-color: #36393F !important;
  color: white !important;
}
<button onclick="myFunction()" class="btndarkmode" id="mode-toggle">Dark mode</button>

Answer №1

In the provided code, I have included comments for better understanding. The code essentially checks whether a button is set to dark mode or light mode. If it is in dark mode, the text content and background color are changed to light mode, and vice versa.

var toggleButton = document.getElementById('mode-toggle')

function myFunction() {
  // To Check if element is in Darkmode
  if(toggleButton.textContent === "Dark mode") {
    toggleButton.textContent = "Light mode"
    toggleButton.style.background = "#eee"
  return
  }
  
  // To Check if element is in Lightmode
   if(toggleButton.textContent === "Light mode") {
     toggleButton.textContent = "Dark mode"
     toggleButton.style.background = "#333"
   return
   }
}
.btndarkmode {
  background-color: #36393F;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btndarkmode:hover {
  background-color: #32353B;
  color: gray;
}

.btnwhitemode {
  background-color: white;
  text-align: center;
  cursor: pointer;
  display: inline-block;
  font-size: 100%;
  font-weight: bold;
  position: fixed;
}

.btnwhitemode:hover {
  background-color: white;
  color: gray;
}

.dark-mode {
  background-color: #36393F !important;
  color: white !important;
}
<button onclick="myFunction()" class="btndarkmode" id="mode-toggle">Dark mode</button>

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

CSS Switchable Style Feature

I am in need of some assistance with the navigation on my website. You can find the current code at this link: http://jsfiddle.net/Sharon_J/cf2bm0vs/ Currently, when you click on the 'Plus' sign, the submenus under that category are displayed bu ...

What might be causing my Vue unit test to overlook a function?

I am in the process of creating unit tests for my component dateFormat.js using Jest. The focus is on testing the function formatDateGlobal. Here is an excerpt from the test: import DateFormat from '../dateFormat'; describe('dateFormat.js& ...

Javascript handles the sorting of elements within an array

I have spent time searching for a solution to my issue, but so far, I have not been successful in finding one. My PHP array is arranged exactly as I need it to be, but when I attempt to display it using JavaScript, the order gets distorted, specifically w ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Using the mouseover event in three.js to interact with child meshes

My array, objMesh, contains multiple mesh objects. Each object has a children attribute, which in turn holds an array of more mesh objects (such as countries and their islands). How can I make it so that when I hover over each mesh object, its children are ...

Mongoose: execute population step after making the query

What is the proper way to populate the query result in Mongoose after executing a query similar to this: users .find({name:"doejohn"}) .skip(3) .limit(9) .exec((err,user) => { user // result ...

What is the best method for validating multiple fields in a form with Javascript?

I am currently working on validating multiple fields within a form. Although I lack experience in JavaScript, I have managed to piece together a code that is functional for the most part. If all fields are left blank, error messages prompt correctly. Howe ...

The Harp server generates excessive white space within HTML documents

Running a blog on Harp has been smooth sailing, except for one issue that I can't seem to figure out. The project utilizes EJS and the problem lies in the outputted HTML containing excessive whitespace. I've attempted to minimize it, especially w ...

Add a variable to the configuration

Here is my configuration setup angular.module('moduleApp.config') .config(['$translateProvider', '$languageSupportProvider', function($translateProvider, $languageSupportProvider) { // Need to access data from myS ...

The presence of inline display causes gaps of white space

Located at the bottom of this webpage is a media gallery. The initial three images comprise the photo gallery, followed by video thumbnails inlined afterwards. However, there seems to be an issue with the alignment of each element within the video gallery. ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

Unlocking the ability to retrieve data generated by the context within getServerSideProps beyond its boundaries (for transitioning from Create React App to Next.js)

I am currently utilizing Create React App for my react application but I am in the process of migrating to Next.js. Accessing URL data such as host, protocol, and query parameters has posed a significant challenge. After some trial and error, I realized t ...

Is there a way to display sorting icons consistently and in a blue color for the currently selected sorting column in a React material-table component?

I recently used the material-table library to create a material table, but I am having trouble displaying the sorting icon continuously for all columns. In addition, I would like the color of the column that is currently sorted to be blue. If you want to ...

update the dropdown values in the database by submitting the form

Members sign up for the website. The administrator will log in and access a list of users. I am attempting to provide an option for the admin to select a checkbox and update the user's status through a dropdown menu submission. When I tested the code ...

The Send.php script is missing the input fields for Name and Email

Running my own website at CrystalVision.com, I have some challenges with my PHP skills. The issue lies within my send.php file. Although the email functionality works fine and I receive messages, the Name and Email fields filled in by users are not display ...

items with sticky positioning on CSS grid

I've searched through various examples, but none seem to solve my issue. I am trying to make the sidebar (section) sticky as the page scrolls. The position:sticky property works when applied to the navigation bar, so it's definitely supported by ...

Tips for accessing the parent method within a jQuery AJAX success function

Similar Question: javascript how to reference parent element Hello everyone! This is my first time posting here. I have a question - how can I trigger alerts from a successful AJAX call? var page = { alerts: function (json) { if (json ...

Examining the words within strings and drawing comparisons

I am attempting to analyze words within strings for comparison purposes. This is my objective: var string1 = "Action, Adventure, Comedy"; var string2 = "Action Horror"; if (string1 contains a word from string 2 == true) { alert("found!"); } I have e ...

"Having trouble getting `justify-between` to work in a tailwind CSS on an absolute

I'm currently using Tailwind CSS and I'm trying to position my navbar on top of an image. The image is set in a relative position and the navbar is set in an absolute position. Surprisingly, when the navbar is not set in the absolute position, I ...

Child Component featuring an Accordion group implemented with ngx-bootstrap

Primary Component <input type="button" class="btn btn-primary" (click)="allExpanded = !allExpanded" [attr.value]="allExpanded ? 'Collapse All': 'Expand All'" > <div class=& ...