When the checkbox is not selected, the content on the page will revert back to its original state

Is there a way to dynamically change content on a page when a checkbox is checked, and revert it back when the checkbox is unchecked? I don't want to manually set each element's value to default in JavaScript and CSS.

<div class="switch">
    <input type="checkbox" name="checkbox" id="checkbox" onchange="darkmode(this)" />
</div>

<section id="section">
    <p>This is a line</p>
</section>
<script>
    function darkmode(checkboxElem) {
        if (checkboxElem.checked) {
            document.body.style.backgroundColor = "black";
            document.getElementById("checkbox").style.borderColor = "white";
            document.getElementById("section").style.color ="white"; 
        } else {
            document.body.style.backgroundColor = "white";
            document.getElementById("checkbox").style.borderColor = "black";
            document.getElementById("section").style.color ="black"; 
        }
    }   
</script>

If you have a solution for resetting all elements to their defaults without specifying individual values in CSS and JavaScript, please share. Thank you!

Answer №1

If you're looking for a simple and effective solution, consider designing your dark mode style tied to a body css class and toggling that class using the onchange event directly.

I hope this solution proves helpful for you.

body.dark-mode{
  background-color:black;
}
  body.dark-mode>h1{
    color:red;
  }
  body.dark-mode>p{
    color:white;
  }
<body>
 <input type='checkbox' onchange='document.body.classList.toggle("dark-mode");'>
 <h1>Heading 1</h1>
 <p>Paragraph 1</p>
 ...
</body>

Answer №2

The simplest approach would involve toggling a class on the body element, as demonstrated in the code snippet below. By defining all the dark mode styles within the CSS and ensuring it's placed after the normal styling, you can easily implement a dark mode feature for your website.

function toggleDarkMode(checkboxElem) {
  var body = document.body;
  if (checkboxElem.checked) {
    body.classList.add("dark-mode");
  } else {
    body.classList.remove("dark-mode");
  }
}
.dark-mode {
  color: white;
  background-color: black;
}
<body>
  <div class="switch">
    <input type="checkbox" name="checkbox" id="checkbox" onchange="toggleDarkMode(this)" />
  </div>

  <section id="section">
    <p>This is a line</p>
  </section>
</body>

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

transform constant values into API requests using React

The sample dataset mentioned will be retrieved from a backend API call handled by Flask. The API has already been configured on the backend. const rows = [ { name: "XYZ", age: "12", email: "<a href="/cdn-cgi/l/emai ...

Customize the MUI (JoyUI) Autocomplete feature in React using react-hook-form to display a unique value instead of the label

Currently, I am in the process of creating a form that includes JoyUI (material) autocomplete and react-hook-form functionality. The array of objects I am using for my options looks like this: [ { label: "Todo", param: "TODO" }, ...

Console command to change paragraph tag color---Modifying the color

I am attempting to change the color of all paragraph tags on a webpage to white by utilizing the console. My initial attempt was: document.p.style.color = 'white'; However, this method did not have the desired effect. Interestingly, I have had s ...

Tips for obtaining a specific sorting order based on a wildcard property name

Here's the structure of my JSON object, and I need to sort it based on properties starting with sort_ { "sort_11832": "1", "productsId": [ "11832", "160", "180" ], "sort_160": "0", "sort_180": " ...

Font size transition on pseudo elements is not functioning properly in Internet Explorer when using the "em" unit

When I hover over, the font awesome icon and text on this transition increase in size. All browsers work well with this effect except for IE 11. This example demonstrates the same transition using px (class test1) and em (class test2). While using px wor ...

Encountering an issue with WebDriver in the realm of JavaScript

I am struggling to use JavaScript to locate specific controls and send values to them. One example is changing the text in a textbox with the ID "ID" to "123456". Below is the code I tried: ((IJavaScriptExecutor)driver).ExecuteScript("document.getElement ...

What is the best way to assign a value to process.env within an npm script?

After creating a new Vue app (using Vite) with npm init vue@latest and selecting Playwright for e2e tests, the configuration file was generated with a field for setting headless mode: const config: PlaywrightTestConfig = { // ... use: { // ... ...

Troubleshooting: Django project not functioning properly post transfer from Windows to Mac

Using Django 3.1.7 on a MacBook Pro now, I recently moved the Django project from a Windows 10 machine. Despite setting up the database and superuser again, running pipenv sync didn't result in serving any of my URLs or Admin page CSS styles. The serv ...

Can someone please help me figure out how to detect active users within my Next.js application while utilizing Supabase authentication?

I'm looking for a way to recognize users on my app in order to display green badges as visual cues. After logging into my app using Google OAuth, the session remains active even though I logged out days ago. I am unsure of the most effective algorith ...

Utilizing NodeJS to Refine JSON Data

I am working with a JSON array that consists of multiple objects. My goal is to retrieve objects that have a specific value, such as returning [ service_wog: { count: 48, popular: false, code: 33, price: 20, id: ...

Extract data from Markit On Demand API using JavaScript and AJAX

I'm struggling to properly parse the response from the API. While I can retrieve the entire response, I am a bit lost on how to effectively parse it. Below is my code snippet: <!DOCTYPE> <html> <head> <style> img ...

How can you calculate the number of elements in a jQuery array and iterate through each of them?

After extracting a string from a mySQL query with PHP, my AJAX script comes into play. This string is then dissected and placed into a jQuery array. The results are displayed on the screen using .html() The length of this array can range from zero items t ...

Is your browser tab failing to display the complete URL?

Encountering a strange issue while working on my current website project: When you click on "about," it does take you to the correct page, but upon refreshing the page, it redirects back to the home page. The same scenario is happening with other pages as ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

Is it possible to alter the state of one page by clicking a link on another page?

Is it possible to update the state of a different page when a link is clicked and the user navigates to that page? For example: Homepage <Link href="/about"> <button>Click here for the About page</button> </Link> If a ...

What is the best way to include the ID in a Vue.js Ajax request for posts?

Is there a way to pass an "id" obtained as data in vue js? The id is coming as "agnt.basic.actor". Considering the presence of multiple ids, how can I achieve this? <tr v-for="agnt in agentlist"> <td v-if="agnt.basic">{{agnt.basic.actor}}< ...

The upload method in flowjs is not defined

I am a novice when it comes to flow.js and am currently using the ng-flow implementation. I have a specific task in mind, but I'm unsure if it's feasible or not, and if it is possible, how to achieve it. I've created a factory that captures ...

Refreshing a sibling component because of data changes in another sibling component within Next JS

I have a Next JS application where I am utilizing the Layout feature within the _app.tsx component. The layout includes a sidebar that is populated from an API call using a GET request. In addition, there is another API call (update request) triggered on ...

Choosing between Vue.prototype, Vue.use, and import for each fileWhen it comes

Discover various techniques for implementing a global function in a Vue.js project: time.js // Option 1: if using Vue.use() export default { install: Vue => { Object.defineProperty(Vue.prototype, "time", { return new Date().getT ...

Creating a stylish zebra pattern using JCrop on the cropping window

Lately, while using jquery jcrop, I've noticed a peculiar design appearing on the cropping window. The details of this pattern are unclear to me. What could be the reason behind the zebra-like pattern visible on the cropping window? Is there any spec ...