Dark Mode is a popular feature with a darker colour scheme, making it easier on the eyes, especially in low-light environments. It enhances the visual appeal and improves user experience by reducing eye strain and saving battery life on OLED screens.
In this tutorial, I'll guide you through the steps to integrate Dark Mode into your Bootstrap-based projects. I'll cover the basics of Bootstrap's colour utilities, demonstrate how to toggle between Light and Dark modes and show you how to save user preferences for a seamless experience.
Whether you're building a personal blog, a professional portfolio, or a dynamic web application, adding Dark Mode will give your site a modern, user-friendly touch. Let's dive in and explore how to effortlessly switch your Bootstrap site to Dark Mode and make your web design more versatile and appealing with Bootstrap.
Insert the dark mode switch in your HTML page and the javascript as shown below.
Switch:
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="darkModeToggle" />
<label class="form-check-label" for="darkModeToggle" id="themeLabel">Dark Mode</label>
</div>
Javascript:
function setTheme(theme){
document.documentElement.setAttribute("data-bs-theme", theme);
localStorage.setItem("theme",theme);
document.getElementById("themeLabel").innerText =
theme === "dark" ? "Dark Mode On" : "Dark Mode Off";
}
document
.getElementById("darkModeToggle")
.addEventListener("change", function (event) {
if (event.target.checked) {
setTheme("dark");
} else {
setTheme("");
}
});
window.onload = function () {
let savedTheme = localStorage.getItem("theme");
if(savedTheme) {
setTheme(savedTheme);
if (savedTheme === "dark") {
document.getElementById("darkModeToggle").checked = true;
}
}
};
The javascript will write current theme to browser local storage to ensure that the selected theme will be used whenever the user open the website.
That all! Happy coding!