Building a Theme Switcher for Bootstrap 5.3+

- 2 mins read

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.

This is the switcher you can see in the left sidebar of this blog, as an example.

Theme Switcher for Bootstrap 5.3+
Theme Switcher for Bootstrap 5.3+

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:


<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 title="Use light mode" id="light" class="btn btn-sm btn-default text-secondary">
        <i class="bi bi-sun"></i>
    <button title="Use system preferred mode" id="system" class="btn btn-sm btn-default text-secondary">
        <i class="bi bi-display"></i>


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) {
  } 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.querySelectorAll('.mode-switch .btn').forEach(e => e.addEventListener('click', () => setTheme(;
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="[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="[email protected]/font/bootstrap-icons.min.css" rel="stylesheet">


Here’s a breakdown of what it does:

  • It provides three buttons for users to switch between light, dark, and system-preferred (which follows the prefers-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.

Share: Link copied to clipboard


Previous: Automating Cache Warmup after Deployments with Bash Script
Next: Testing the new Alibaba Cloud g8y ECS Instances

Where: Home > Technical > Building a Theme Switcher for Bootstrap 5.3+