Dark Mode Toggle With jQuery And Local Storage

File Size: 10 KB
Views Total: 4200
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Dark Mode Toggle With jQuery And Local Storage

Yet another dark mode toggle that enables the visitor to toggle between Dark Mode and Light Mode with a smooth color transition effect.

It uses jQuery to toggle between CSS classes and utilizes local storage API to persistent the dark mode across pages and refreshes.

See Also:

How to use it:

1. Apply dark mode styles to your webpage as follows:

body {
  color: #222;
  -webkit-transition: background-color 800ms ease;
  transition: background-color 800ms ease;
}

body.dark {
  background-color: #222;
  color: #fff;
}

body.dark img {
  -webkit-filter: brightness(70%);
  filter: brightness(70%);
}

/* more dark mode styles here */

2. Create Dark/Light Mode toggle buttons on the page.

<button class="dark-button">Dark</button>
<button class="light-button" hidden="hidden">Light</button>

3. Load the necessary jQuery library at the end of the document.

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

4. The main JavaScript to setup the dark mode.

var darkMode;

if (localStorage.getItem('dark-mode')) {  
  // if dark mode is in storage, set variable with that value
  darkMode = localStorage.getItem('dark-mode');  
} else {  
  // if dark mode is not in storage, set variable to 'light'
  darkMode = 'light';  
}

// set new localStorage value
localStorage.setItem('dark-mode', darkMode);


if (localStorage.getItem('dark-mode') == 'dark') {
  // if the above is 'dark' then apply .dark to the body
  $('body').addClass('dark');  
  // hide the 'dark' button
  $('.dark-button').hide();
  // show the 'light' button
  $('.light-button').show();
}

5. Enable the Dark/Light Mode toggle buttons

$('.dark-button').on('click', function() {  
  $('.dark-button').hide();
  $('.light-button').show();
  $('body').addClass('dark');  
  // set stored value to 'dark'
  localStorage.setItem('dark-mode', 'dark');
});

$('.light-button').on('click', function() {  
  $('.light-button').hide();
  $('.dark-button').show();
  $('body').removeClass('dark');
  // set stored value to 'light'
  localStorage.setItem('dark-mode', 'light');   
});

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