Give your website visitors a better viewing experience with this easy-to-implement Dark Mode Toggle Switch. This modern feature reduces eye strain in low-light environments and is a highly requested user preference. This script is built with pure, lightweight vanilla JavaScript and modern CSS, requiring no database and no external libraries like jQuery.
Features:
- One-Click Theme Switching: Instantly toggle between a light and dark theme.
- Remembers User's Choice: Uses browser
localStorage
to save the user's selected theme, so it persists when they revisit your site. - Respects OS Preference: Automatically detects the user's operating system setting (light or dark mode) on their first visit.
- Easy Color Customization: All theme colors are controlled by simple CSS variables. Just change a few lines of code to match your brand.
- No Database Needed: A completely front-end solution that's incredibly easy to set up.
How to Use:
- Add the HTML: Copy the HTML for the toggle switch from the
index.html
file and place it in your website's header or footer where you want the switch to appear. - Link the CSS: Add the link to the
style.css
file inside the<head>
of your website. - Link the JavaScript: Add the script tag for
script.js
right before the closing</body>
tag of your website. - Customize Colors: Open
style.css
and edit the color values in the:root
(for light mode) and[data-theme="dark"]
(for dark mode) sections to match your website's design.