Hey team, here's the plan:
First, make sure to include this .js file in your project:
export class ThemeManager {
'use-strict';
/**
* ThemeManager class object constructor
* @param {string} themeToggle - element that changes website theme on click
* @param {string} theme - light for initial theme light, dark for dark theme
*/
constructor(themeToggle, theme = 'light') {
// get theme toggle element
if (!themeToggle) {
console.error(`A valid DOM element must be passed as the themeToggle. You passed ${themeToggle}`);
return;
}
this.themeToggle = themeToggle;
this.themeToggle.addEventListener('click', () => this.switchTheme());
// set initial theme and apply
this.theme = theme;
if (localStorage.getItem('data-theme')) {
if (localStorage.getItem('data-theme') === (theme === 'light' ? 'dark' : 'light')) {
this.theme = (theme === 'light' ? 'dark' : 'light');
}
}
else if (window.matchMedia(`(prefers-color-scheme: ${(theme === 'light' ? 'dark' : 'light')})`).matches) {
this.theme = (theme === 'light' ? 'dark' : 'light');
}
this._applyTheme();
// add listener to change web theme on os theme change
window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', (e) => {
this.theme = (e.matches ? 'light' : 'dark');
this._applyTheme();
});
}
/**
* Private _applyTheme sets documentElement and localStorage 'data-theme' attribute
* changing page style based on 'data-theme'
*/
_applyTheme = () => {
this.themeToggle.innerHTML = (this.theme === 'light' ? 'Dark' : 'Light');
document.documentElement.setAttribute('data-theme', this.theme);
localStorage.setItem('data-theme', this.theme);
}
/**
* switchTheme toggles website theme on themeToggle 'click'
*/
switchTheme = () => {
this.theme = (this.theme === 'light' ? 'dark' : 'light');
this._applyTheme();
}
}
Next, add this css to your pages .css file:
/* Dark/Light Mode Support Modifications
-------------------------------------------------- */
a, a:hover {
color: var(--link-white-color);
}
.dropdown-menu {
background: var(--bg-color);
}
.dropdown-item {
color: var(--link-white-color);
}
hr {
background-color: var(--link-white-color);
height: 1px;
border: 0;
}
/* Dark/Light Mode Support
-------------------------------------------------- */
/*Light*/
:root {
--font-color: #000;
--link-color: #1C75B9;
--link-white-color: #000;
--bg-color: rgb(243,243,243);
}
/*Dark*/
[data-theme="dark"] {
--font-color: #c1bfbd;
--link-color: #0a86da;
--link-white-color: #c1bfbd;
--bg-color: #333;
}
Finally, in your html file, simply add this:
<html>
<head>
<title>your_title</title>
<link rel="stylesheet" href="path/to/your/css">
</head>
<body>
<button id="themeToggle"></button>
<script type="module" src="path/to/ThemeManager.js"></script>
<script type="module">
import {ThemeManager} from 'path/to/ThemeManager.js';
new ThemeManager(document.getElementById('themeToggle'));
</script>
</body>
</html>