javascript - Use Single button to toggle two functions for easy Light and Dark Mode - TagMerge
3Use Single button to toggle two functions for easy Light and Dark ModeUse Single button to toggle two functions for easy Light and Dark Mode

Use Single button to toggle two functions for easy Light and Dark Mode

Asked 5 months ago
3
3 answers

Here ya go, with some flare from a switch I made awhile back anyway. If you want verification just open your dev tools and watch the data attribute of the example HTML change live.

const htmlEl = document.documentElement,
      outputExample = document.getElementById('output');
      
let savedTheme = 'light';

// ********************************************************************
//  NOTE: The localStorage example WILL NOT WORK HERE ON STACKOVERFLOW
//        Instead it will throw a "SecurityError" and rightfully so...
//        You'll have to use that part of the example in your
//        own project to see it in action...... JUST FYI.
//        So you will need to UNCOMMENT the commented out stuff for
//        the localstorage example to work. Left it commented out for
//        for other readers to not see the valid securityerror....
// ********************************************************************

// Toggle the theme and update their local storage.
toggleTheme = (bool) => {
   const theme = bool ? 'light' : 'dark';
   htmlEl.dataset.theme = theme;
   // localStorage.setItem('savedTheme', theme);
   
   outputExample.innerText = `${theme} theme`;
}

// Handle their saved preferred theme.
setSavedTheme = () => {

  // If there is no current theme in localstorage then give them one as a default.
  // Like for first time visitors...
  // Uncomment this block and the localstorage piece above for the localstorage example.
  /*
  if (localStorage.getItem('savedTheme') === null) {
    localStorage.setItem('savedTheme', savedTheme);
  } else {
    savedTheme = localStorage.getItem('savedTheme');
  }
  */
  
  htmlEl.dataset.theme = savedTheme;
  outputExample.innerText = `${savedTheme} theme`;
}

// Set the default.
setSavedTheme();
.slide-toggle {
  position: relative;
  font-weight: 600;
  display: inline-block;
  border-radius: 3px;
}
.slide-toggle input:first-of-type {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
.slide-toggle input:first-of-type:focus ~ label {
  box-shadow: 0 0 0 6px rgba(255, 0, 0, 0.15);
}
.slide-toggle input:first-of-type:checked ~ label {
  color: #fff;
  background-color: darkorange;
}
.slide-toggle input:first-of-type:checked ~ label:after {
  transform: translateX(100%);
}
.slide-toggle input:first-of-type:disabled ~ label {
  opacity: 0.5;
  pointer-events: none;
}
.slide-toggle label:first-of-type {
  display: flex;
  height: 2rem;
  width: 4rem;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  user-select: none;
  outline: none;
  color: #777;
  background-color: #ddd;
  border-radius: 3px;
  transition: background-color 0.25s ease, box-shadow 0.15s ease, color 0.25s ease;
}
.slide-toggle label:first-of-type:hover {
  border-color: #777;
  box-shadow: 0 0 0 6px rgba(225, 0, 0, 0.15);
}
.slide-toggle label:first-of-type:after {
  content: "";
  position: absolute;
  top: 3px;
  bottom: 3px;
  left: 3px;
  right: 50%;
  border-radius: 3px;
  background-color: #fff;
  transition: transform 0.25s cubic-bezier(0.6, 0.82, 0, 0.76);
}
.slide-toggle label:first-of-type:hover {
  box-shadow: 0 0 0 6px rgba(225, 0, 0, 0.15);
}
.slide-toggle label:first-of-type div {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
}

html {
  transition: background-color .3s ease;
}

html[data-theme="light"] {
  background-color: #fff;
}

html[data-theme="dark"] {
  color: #fff;
  background-color: #212121;
}

body {
  height: 50vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">

<div class="slide-toggle">
  <input id="guidLater"
         type="checkbox" checked
         onchange="toggleTheme(this.checked)"/>
  <label for="guidLater">
    <div><i class="fas fa-sun"></i></div>
    <div><i class="fas fa-moon"></i></div>
  </label>
</div>

<div id="output" style="margin-top: 1rem"></div>

Source: link

0

btn.addEventListener('click', function() {
  var foo = 'dark';
 
    if (foo === "light") {
        toggleTheme('dark');
    } else {
        toggleTheme('light');
    }

}, false);

Is wrong.

You need to grab the current theme from the clicked on element (you have it set in data-theme attribute of the element).

Your code just sets the theme as "dark" every time a button is clicked, rather than actually accepting the current value, and toggling it.


btn.addEventListener('click', function(event) {
  var currentTheme= event.currentTarget.dataset.theme;
 
    if (currentTheme=== "light") {
        toggleTheme('dark');
    } else {
        toggleTheme('light');
    }

}, false);

Also, remove your inline calls of toggleTheme, and only call the function from the handler on the click event listener.

<button data-theme="dark">Dark Mode Test</button>
    
<button data-theme="light">Light Mode Test</button>

Source: link

0

The trick here is to swap out a class that can be a hook for changing a style anywhere on the page.
<body class="dark-theme || light-theme">
Here’s a script for a button that will toggle that class, for example:
// Select the button
const btn = document.querySelector('.btn-toggle');

// Listen for a click on the button
btn.addEventListener('click', function() {
  // Then toggle (add/remove) the .dark-theme class to the body
  document.body.classList.toggle('dark-theme');  
})
Here’s how we can use that idea:
<body>
  <button class="btn-toggle">Toggle Dark Mode</button>
  <h1>Hey there! This is just a title</h1>
  

I am just a boring text, existing here solely for the purpose of this demo

 

And I am just another one like the one above me, because two is better than having only one

  <a href="#">I am a link, don't click me!</a> </body>
Let’s say our default is a light color scheme. All of those “light” styles are written exactly the same way you normally write CSS. Given our HTML, let’s apply some global styling to the body and to links.
body {
  color: #222;
  background: #fff;
}
a {
  color: #0033cc;
}
Now let’s redefine those property values, this time set on a different body class:
body {
  color: #222;
  background: #fff;
}
a {
  color: #0033cc;
}


/* Dark Mode styles */
body.dark-theme {
  color: #eee;
  background: #121212;
}
body.dark-theme a {
  color: #809fff;
}

Source: link

Recent Questions on javascript

    Programming Languages