I attempted different approaches to replace the existing checkbox with a button but encountered difficulty. Using the onClick method also proved unsuccessful.
VIEW DEMO HERE: https://jsfiddle.net/yxez4a2u/
HTML:
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="darkModeSwitch" checked>
<label class="form-check-label" for="darkModeSwitch">Dark Mode</label>
</div>
<button type="button" onclick="darkModeSwitch('light')"> Light </button>
<button type="button" onclick="darkModeSwitch('dark')"> Dark </button>
<p>
This showcases Bootstrap 5 color mode functionality with storage capabilities.
</p>
JS:
document.addEventListener('DOMContentLoaded', (event) => {
const htmlElement = document.documentElement;
const switchElement = document.getElementById('darkModeSwitch');
// Set default theme to dark if no setting is found in local storage
const currentTheme = localStorage.getItem('bsTheme') || 'light';
htmlElement.setAttribute('data-bs-theme', currentTheme);
switchElement.checked = currentTheme === 'light';
switchElement.addEventListener('change', function () {
if (this.checked) {
htmlElement.setAttribute('data-bs-theme', 'light');
localStorage.setItem('bsTheme', 'light');
} else {
htmlElement.setAttribute('data-bs-theme', 'dark');
localStorage.setItem('bsTheme', 'dark');
}
});
});