Create a button which switches the page to dark mode

Description: A button must switch the page between light and dark mode.

Hint:

  • Change the attribute data-bs-theme of the html element.

Solution

<button type="button" class="btn btn-outline-secondary" id="themeSwitch">Switch theme</button>
<script>
  document.getElementById('themeSwitch').addEventListener('click', function () {
    var root = document.documentElement;
    root.setAttribute('data-bs-theme', root.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark');
  });
</script>
Live preview

const bg = () => getComputedStyle(document.body).backgroundColor;
console.log('start: ' + (document.documentElement.getAttribute('data-bs-theme') || 'light') + ' -> ' + bg());
document.getElementById('themeSwitch').click();
console.log('after the 1st click: ' + document.documentElement.getAttribute('data-bs-theme') + ' -> ' + bg());
document.getElementById('themeSwitch').click();
console.log('after the 2nd click: ' + document.documentElement.getAttribute('data-bs-theme') + ' -> ' + bg());
Console output (real Chrome)

start: light -> rgb(255, 255, 255)
after the 1st click: dark -> rgb(33, 37, 41)
after the 2nd click: light -> rgb(255, 255, 255)

How it works

  • Bootstrap colors come from CSS variables, which change when data-bs-theme changes.
  • To remember the choice of the user, also save it in localStorage.

Read Color Modes.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.