bootstrap-darkmode
Version:
Stylesheet and Scripts for implementing dark mode with Bootstrap 4
59 lines (55 loc) • 1.64 kB
JavaScript
class ThemeConfig {
constructor() {
this.themeChangeHandlers = [];
}
loadTheme() {
return localStorage.getItem('theme');
}
saveTheme(theme) {
if (theme === null) {
localStorage.removeItem('theme');
}
else {
localStorage.setItem('theme', theme);
}
}
initTheme() {
this.displayTheme(this.getTheme());
}
detectTheme() {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
getTheme() {
return this.loadTheme() || this.detectTheme();
}
setTheme(theme) {
this.saveTheme(theme);
this.displayTheme(theme);
}
displayTheme(theme) {
document.body.setAttribute('data-theme', theme);
for (let i = 0; i < this.themeChangeHandlers.length; i++) {
this.themeChangeHandlers[i](theme);
}
}
}
function writeDarkSwitch(config) {
document.write(`
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="darkSwitch">
<label class="custom-control-label" for="darkSwitch">Dark Mode</label>
</div>
`);
const darkSwitch = document.getElementById('darkSwitch');
darkSwitch.checked = config.getTheme() === 'dark';
darkSwitch.onchange = () => {
config.setTheme(darkSwitch.checked ? 'dark' : 'light');
};
config.themeChangeHandlers.push(theme => darkSwitch.checked = theme === 'dark');
return darkSwitch;
}
/**
* Generated bundle index. Do not edit.
*/
export { ThemeConfig, writeDarkSwitch };
//# sourceMappingURL=bootstrap-darkmode.mjs.map