Building a Theme Switcher for Bootstrap 5.3+

- 05 March 2024 - 3 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 approach to user interface customization is similar to how we handle themes in our DevOps tools, where consistency and user experience are key priorities.

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. For more examples of modern web development practices, check out our guide on building serverless applications.

Also, 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:

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 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.

This theme switcher is a great example of how modern web development can enhance user experience. For more insights into building user-friendly interfaces, check out our article on remote business development, where we discuss the importance of accessible and adaptable web tools.


Share: Link copied to clipboard

Tags:

Previous: Por qué sigo escribiendo en mi blog en 2024
Next: Testing the new Alibaba Cloud g8y ECS Instances

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