Toggle Between Dard Mode And Light Mode With A Switch Button

Toggle Between Dard Mode And Light Mode With A Switch Button
File Size: 1.95 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A simple dark mode switcher that allows the visitor to toggles between dark theme and light theme with a pure CSS toggle button.

See also:

How to use it:

1. Create the dark mode switcher from a regular checkbox input.

<input type="checkbox" class="toggle-switch">

2. Convert the checkbox into a switch.

input[type=checkbox].toggle-switch {
  transform: rotate(90deg);
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  outline: 0;
  cursor: pointer;
  /* width of the track */
  width: 4em;
  /* height of the track */
  height: 1.5em;
  border-radius: 3em;
  background-color: #ebebeb;
  transition: background-color 0.09s ease-in-out;
  position: relative;
}

input[type=checkbox].toggle-switch:active::after {
  background-color: #f2f2f2;
  padding-right: .8em;
}

input[type=checkbox].toggle-switch::after {
  content: '';
  width: 2em;
  height: 2em;
  background-color: white;
  border-radius: 3em;
  position: absolute;
  left: -5px;
  top: 50%;
  transform: translateY(-50%);
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;
  box-shadow: 2px 0px 5px 0 rgba(0, 0, 0, 0.15);
}

input[type=checkbox].toggle-switch:checked {
  background-color: #333;
}

input[type=checkbox].toggle-switch:checked:active::after {
  margin-left: -.8em;
}

input[type=checkbox].toggle-switch:checked::after {
  left: 2em;
  background-color: #242424;
}

3. Load the jQuery library (slim build) at the end of the document.

<script src="/path/to/jquery.slim.min.js"></script>

4. The JavaScript (jQuery script) to toggle the CSS class when you click the switch.

$(".toggle-switch").on("click", function(event){
  $("body").toggleClass("dark");
});

5. Style the page elements when in the dark mode.

.dark {
  background: #181818;
  color: #fff;
}

This awesome jQuery plugin is developed by russpate. For more Advanced Usages, please check the demo page or visit the official website.