2020-10-25 10:08:07 +01:00
|
|
|
|
(function(){
|
2023-01-10 05:07:57 +01:00
|
|
|
|
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// Select the button
|
2020-12-21 03:10:43 +01:00
|
|
|
|
const btnTheme = document.getElementById('theme');
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// Check for dark mode preference at the OS level
|
2020-12-21 03:10:43 +01:00
|
|
|
|
const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
|
2020-10-25 10:08:07 +01:00
|
|
|
|
|
|
|
|
|
// Get the user's theme preference from local storage, if it's available
|
2020-12-21 03:10:43 +01:00
|
|
|
|
const currentTheme = localStorage.getItem('theme');
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// If the user's preference in localStorage is dark...
|
2023-01-10 05:07:57 +01:00
|
|
|
|
if (currentTheme === 'dark') {
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// ...let's toggle the .dark-theme class on the body
|
2020-12-21 03:10:43 +01:00
|
|
|
|
document.body.classList.toggle('dark-theme');
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// Otherwise, if the user's preference in localStorage is light...
|
2023-01-10 05:07:57 +01:00
|
|
|
|
} else if (currentTheme === 'light') {
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// ...let's toggle the .light-theme class on the body
|
2020-12-21 03:10:43 +01:00
|
|
|
|
document.body.classList.toggle('light-theme');
|
2020-10-25 10:08:07 +01:00
|
|
|
|
}
|
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
|
// Listen for a click on the button
|
|
|
|
|
btnTheme.addEventListener('click', function(e) {
|
|
|
|
|
e.preventDefault();
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// If the user's OS setting is dark and matches our .dark-theme class...
|
2023-01-10 05:07:57 +01:00
|
|
|
|
let theme;
|
2020-10-25 10:08:07 +01:00
|
|
|
|
if (prefersDarkScheme.matches) {
|
|
|
|
|
// ...then toggle the light mode class
|
2020-12-21 03:10:43 +01:00
|
|
|
|
document.body.classList.toggle('light-theme');
|
2020-10-25 10:08:07 +01:00
|
|
|
|
// ...but use .dark-theme if the .light-theme class is already on the body,
|
2023-01-10 05:07:57 +01:00
|
|
|
|
theme = document.body.classList.contains('light-theme') ? 'light' : 'dark';
|
2020-10-25 10:08:07 +01:00
|
|
|
|
} else {
|
|
|
|
|
// Otherwise, let's do the same thing, but for .dark-theme
|
2020-12-21 03:10:43 +01:00
|
|
|
|
document.body.classList.toggle('dark-theme');
|
2023-01-10 05:07:57 +01:00
|
|
|
|
theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light';
|
2020-10-25 10:08:07 +01:00
|
|
|
|
}
|
|
|
|
|
// Finally, let's save the current preference to localStorage to keep using it
|
2020-12-21 03:10:43 +01:00
|
|
|
|
localStorage.setItem('theme', theme);
|
2020-10-25 10:08:07 +01:00
|
|
|
|
});
|
|
|
|
|
|
2023-01-10 05:07:57 +01:00
|
|
|
|
})();
|