DeshAmarBD
Home » Web Design » How To Toggle Between Dark and Light Mode

How To Toggle Between Dark and Light Mode

Switch between dark and light mode with CSS and JavaScript.

HTML Code:

Use any element that should store the content you want to toggle the design for. In our example, we will use <body> for the sake of simplicity:

<input type="checkbox" id="darkSwitch">

CSS Code:

Turning dark mode on will add data-theme=”dark to the body tag. You can use CSS to target the elements on the page like so:

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

Add Class:

[data-theme="dark"] .bg-black {
  background-color: #fff !important;
}

Full Code:

*,*::before,*::after{
  margin:0;
  padding:0;
  box-sizing:border-box;
}
body{
  display:flex;
  align-items:center;
  justify-content:center;
  min-height:100vh;
  background:#fff;
  color: #1e293b;
  font-size: 2rem;
  font-family: sans-sarif;
}
[data-theme="dark"]{
  background-color: #1e293b;
  color: #fff;
}
input {
  position: relative;
  margin: 0 10px;
  width: 100px; 
  height: 50px;
  border-radius: 25px;
  background: #999;
  outline: 0;
  -webkit-appearance: none;
  cursor: pointer;
}
input::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  display: block;
  width: calc((100% - 4px) / 2);
  height: calc(100% - 4px);
  border-radius: 50%;
  background: #eee;
  transition: all .1s linear;
}
input:checked {
  background: #5b5;
}
input:checked::after {
  transform: translateX(100%);
}

JavaScript Code:

var darkSwitch = document.getElementById("darkSwitch");
window.addEventListener("load", function () {
  if (darkSwitch) {
    initTheme();
    darkSwitch.addEventListener("change", function () {
      resetTheme();
    });
  }
});

function initTheme() {
  var darkThemeSelected =
    localStorage.getItem("darkSwitch") !== null &&
    localStorage.getItem("darkSwitch") === "dark";
  darkSwitch.checked = darkThemeSelected;
  darkThemeSelected
    ? document.body.setAttribute("data-theme", "dark")
    : document.body.removeAttribute("data-theme");
}

function resetTheme() {
  if (darkSwitch.checked) {
    document.body.setAttribute("data-theme", "dark");
    localStorage.setItem("darkSwitch", "dark");
  } else {
    document.body.removeAttribute("data-theme");
    localStorage.removeItem("darkSwitch");
  }
}

RH Suman

Add comment

Leave a Reply

AdBlocker Message

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.