In this article, I’ll guide you through the process of creating a simple theme switcher using JavaScript and Bootstrap 5.3+. This switcher allows users to seamlessly toggle between light, dark, and system-preferred, providing a personalized browsing experience.
Why 5.3+ compatibility? Since 5.3, Bootstrap supports theming natively and comes with a dark and a light mode. This code will help you switch between those themes easily.
Also, this is the switcher you can see in the left sidebar of this blog, as an example.
HTML and Javascript
First, let’s set up the HTML structure for our theme switcher. Place the following code snippet within your HTML file, wherever you want to place the buttons for users to change the theme:
HTML
<div class="mode-switch">
<button title="Use dark mode" id="dark" class="btn btn-sm btn-default text-secondary">
<i class="bi bi-moon"></i>
</button>
<button title="Use light mode" id="light" class="btn btn-sm btn-default text-secondary">
<i class="bi bi-sun"></i>
</button>
<button title="Use system preferred mode" id="system" class="btn btn-sm btn-default text-secondary">
<i class="bi bi-display"></i>
</button>
</div>
Javascript
function setTheme (mode = 'auto') {
const userMode = localStorage.getItem('bs-theme');
const sysMode = window.matchMedia('(prefers-color-scheme: light)').matches;
const useSystem = mode === 'system' || (!userMode && mode === 'auto');
const modeChosen = useSystem ? 'system' : mode === 'dark' || mode === 'light' ? mode : userMode;
if (useSystem) {
localStorage.removeItem('bs-theme');
} else {
localStorage.setItem('bs-theme', modeChosen);
}
document.documentElement.setAttribute('data-bs-theme', useSystem ? (sysMode ? 'light' : 'dark') : modeChosen);
document.querySelectorAll('.mode-switch .btn').forEach(e => e.classList.remove('text-body'));
document.getElementById(modeChosen).classList.add('text-body');
}
setTheme();
document.querySelectorAll('.mode-switch .btn').forEach(e => e.addEventListener('click', () => setTheme(e.id)));
window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => setTheme());
For this, we need both the Bootstrap 5.3+ and Bootstrap Icons libraries. For this, include them in the <head>
:
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css" rel="stylesheet">
Breakdown
Here’s a breakdown of what it does:
- It provides three buttons for users to switch between
light
,dark
, and system-preferred (which follows theprefers-color-scheme
). - It stores the user’s preferred theme mode in
localStorage
. - It updates the Bootstrap 5.3+ HTML
data-bs-theme
attribute to reflect the chosen theme. - It adds
click
event listeners to the theme-switching buttons to update the theme. - It listens for changes in the system-wide
prefers-color-scheme
and adjusts the site’s theme accordingly.