
This JavaScript snippet enables automatic dark mode switching in your Bootstrap 5 projects.
It applies user theme preferences and maintains them across sessions using local storage.
How It Works:
The script listens for the DOM content to load. It then retrieves the HTML element and the switch element.
It checks local storage for a saved theme preference. If none exists, it defaults to dark mode. The script applies the theme by setting the ‘data-bs-theme’ attribute on the HTML element and adjusts the switch state accordingly.
An event listener on the switch toggles between light and dark themes when clicked. It updates the ‘data-bs-theme’ attribute and saves the new preference to local storage.
How To Use It:
1. Add the dark mode switch to your Bootstrap project:
<div class="form-check form-switch">
<input
class="form-check-input"
type="checkbox"
id="darkModeSwitch"
checked
aria-label="Switch between light and dark mode"
data-bs-toggle="tooltip"
data-bs-placement="top"
title="Switch between light and dark mode">
<label
class="form-check-label"
for="darkModeSwitch">
Dark Mode
</label>
</div>2. Add the following JavaScript code to your project, ideally within a script tag at the end of your HTML body or in a separate JavaScript file:
document.addEventListener('DOMContentLoaded', (event) => {
const htmlElement = document.documentElement;
const switchElement = document.getElementById('darkModeSwitch');
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)").matches;
const currentTheme = localStorage.getItem('bsTheme') || (prefersDarkScheme ? 'dark' : 'light');
htmlElement.setAttribute('data-bs-theme', currentTheme);
switchElement.checked = currentTheme === 'dark';
switchElement.addEventListener('change', function () {
const newTheme = this.checked ? 'dark' : 'light';
htmlElement.setAttribute('data-bs-theme', newTheme);
localStorage.setItem('bsTheme', newTheme);
});
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
});






