Smart Dark Mode Toggle Based On prefers-color-scheme And localStorage

Category: Color , Javascript | March 29, 2023
Authorrobsd
Last UpdateMarch 29, 2023
LicenseMIT
Views327 views
Smart Dark Mode Toggle Based On prefers-color-scheme And localStorage

js-toggle-dark-mode is an intelligent script designed to manage dark mode settings on websites and web apps.

It detects and inherits the user’s preferred color scheme (either dark or light) based on their browser or operating system settings. In addition, this script empowers users by allowing them to override the detected preference and toggle between dark and light modes. Their choice is then stored in the local storage, enabling site-wide consistency and retaining their preference for future visits.

How to use it:

1. Prepare your own dark & light stylesheets.

<link rel="stylesheet" src="css/light-theme.css" id="theme-stylesheet">
<!-- <link rel="stylesheet" src="css/dark-theme.css" id="theme-stylesheet"> -->

2. Create a toggle element that allows the user to toggle between Dark Mode and Light Mode manually.

<div id="theme-toggler"></div>
3. Load the main script right before the closing body tag.
<script src="js/script.js"></script>

You Might Be Interested In:


Leave a Reply