Implement Automatic Dark Mode In Bootstrap 5 With JS

Category: Javascript | June 19, 2023
Author:shaack
Views Total:2,284 views
Official Page:Go to website
Last Update:June 19, 2023
License:MIT

Preview:

Implement Automatic Dark Mode In Bootstrap 5 With JS

Description:

Turning on dark mode in Bootstrap projects is now a breeze, thanks to the much-awaited inclusion of dark mode in Bootstrap 5.3.0.

Bootstrap now supports color modes, starting with dark mode! With v5.3.0 you can implement your own color mode toggler and apply the different color modes as you see fit. We support a light mode (default) and now dark mode. Color modes can be toggled globally on the <html> element, or on specific components and elements, thanks to the data-bs-theme attribute.

This script uses Window.matchMedia method and the CSS prefers-color-scheme query to detect if a user has light or dark mode set as their default. If dark mode is preferred, it automatically adds the data-bs-theme="dark" attribute to the <html> tag to enable Bootstrap’s dark theme.

How to use it:

1. Ensure your project uses Bootstrap 5.3.0 or later.

2. Add the data-bs-theme="auto" attribute to the <HTML> tag.

<html lang=”en” data-bs-theme=”auto”>

3. Include the JavaScript snippet in your HTML file.

;(function () {
  const htmlElement = document.querySelector("html")
  if(htmlElement.getAttribute("data-bs-theme") === 'auto') {
    function updateTheme() {
      document.querySelector("html").setAttribute("data-bs-theme",
      window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
    }
     window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', updateTheme)
    updateTheme()
  }
})()

Changelog:

06/19/2023

  • auto dark mode is now only enabled, if you set the data-bs-theme to `auto`

You Might Be Interested In:


Leave a Reply