Color Mode

Use color-mode.js for better support for Bootstrap’s color modes.

The script automatically detects if the user uses light or dark mode and sets the data-bs-theme attribute to the document element (<html>). It also updates it if the color mode changes. It also exports these functions:

  • getStored() - Returns what is stored ("light", "dark" or null).
  • getPreferred() - Returns current color mode ("light" or "dark").
  • set(colorMode: string) - Let’s you set the color mode.
  • init() - Let’s you reinitialize manually. Will automatically executed when the script loaded and when the color mode changes.

Color Mode Switch

Example about, how you could create a color mode switch.

Code
<div class="form-floating">
    <select class="form-select w-auto" id="colorModeSelect" aria-label="Selector for color mode">
        <option value="auto">Auto</option>
        <option value="light">Light</option>
        <option value="dark">Dark</option>
    </select>
    <label for="colorModeSelect">Select</label>
</div>

<script>
    const initColorModeSelect = () =>
        (colorModeSelect.value = blueWeb.colorMode.getStored() ? blueWeb.colorMode.getPreferred() : "auto")

    document.addEventListener("DOMContentLoaded", initColorModeSelect)
    window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", initColorModeSelect)

    colorModeSelect.addEventListener("change", ({ target }) => {
        blueWeb.colorMode.set(target.value)
    })
</script>

Grab the code

When you don't use the entire Blue Web library, you can also just copy and paste the required code into your own project.

  1. Copy and paste the following code into your project. Source: @/src/js/color-mode.ts