PairDrop/public/scripts/theme.js

40 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-10-25 10:08:07 +01:00
(function(){
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...
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...
} 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
}
// 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...
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,
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');
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
});
})();