Theme Switcher Icon

This helper function for the Theme Switcher change the Theme Switcher icon in the navbar to the one that has been clicked in the dropdown menu. It works with any SVG icon. If you aren't using svg icons you need to alter the script to handle your type of icons. It also change all tables on the page to be dark if dark mode is chosen

Theme Switcher

Drop the Theme Switcher component into your navbar or use the floating Theme Switcher from the online library if you don't have a navbar

Javascript

Add this javascript snippet to a javascript file in your design

class ThemeChecker {
  constructor() {
    this.theme = localStorage.getItem('theme') || 'auto';
    this.togglers = document.querySelectorAll('[data-bs-theme-value]');
    this.tables = document.querySelectorAll('.table');
    this.init();
  }

  toggleIcon(themeIcon) {
    if (themeIcon) {
      document.querySelectorAll('.theme-switcher').forEach((switcher) => {
        const bssThemeIcon = switcher.querySelector('svg');
        bssThemeIcon.innerHTML = '';
        bssThemeIcon.appendChild(themeIcon.cloneNode(true));
      });
    }
  }

  updateTableClasses() {
    this.tables.forEach((table) => {
      document.documentElement.dataset.bsTheme === 'dark' ? table.classList.add('table-dark') : table.classList.remove('table-dark');
    });
  }

  init() {
    const themeObserver = new MutationObserver(() => this.updateTableClasses());
    themeObserver.observe(document.documentElement, { attributeFilter: ['data-bs-theme'] });
    this.updateTableClasses();
    const thisIcon = document.querySelector(`[data-bs-theme-value="${this.theme}"] svg`);
    this.toggleIcon(thisIcon);
    this.togglers.forEach((toggle) => {
      toggle.addEventListener('click', (e) => {
        e.preventDefault();
        const icon = toggle.querySelector('svg');
        this.toggleIcon(icon);
      });
    });
  }
}

document.addEventListener('DOMContentLoaded', () => {
  new ThemeChecker();
});