PairDrop/client/scripts/theme.js

37 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-10-25 10:08:07 +01:00
(function(){
// 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...
2020-12-21 03:10:43 +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...
2020-12-21 03:10:43 +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
}
// Listen for a click on the button
2020-12-21 03:10:43 +01:00
btnTheme.addEventListener('click', function() {
2020-10-25 10:08:07 +01:00
// If the user's OS setting is dark and matches our .dark-theme class...
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,
2020-12-21 03:10:43 +01:00
var 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');
var 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
});
})();