Improve JS code
This commit is contained in:
@@ -1,20 +1,25 @@
|
||||
document.addEventListener('DOMContentLoaded', ready, false);
|
||||
|
||||
const THEME_PREF_STORAGE_KEY = "theme-preference";
|
||||
const GOKARNA_LIGHT_THEME = 'gokarna-light';
|
||||
const GOKARNA_DARK_THEME = 'gokarna-dark';
|
||||
const THEME_TO_ICON_CLASS = {
|
||||
'dark': 'fa fa-sun-o',
|
||||
'light':'fa fa-moon-o'
|
||||
};
|
||||
let toggleIcon = '';
|
||||
let darkThemeCss = '';
|
||||
|
||||
function ready() {
|
||||
toggleIcon = document.querySelector('#dark-theme-toggle span');
|
||||
darkThemeCss = document.getElementById("dark-theme");
|
||||
|
||||
// TODO: Fetch programatically by user's system preference
|
||||
const savedTheme = localStorage.getItem(THEME_PREF_STORAGE_KEY) || GOKARNA_LIGHT_THEME;
|
||||
const savedTheme = localStorage.getItem(THEME_PREF_STORAGE_KEY) || 'light';
|
||||
setTheme(savedTheme);
|
||||
document.getElementById('dark-theme-toggle').addEventListener('click', () => {
|
||||
if (toggleIcon.className === "fa fa-moon-o") {
|
||||
setTheme(GOKARNA_DARK_THEME);
|
||||
} else if (toggleIcon.className === "fa fa-sun-o") {
|
||||
setTheme(GOKARNA_LIGHT_THEME);
|
||||
if (toggleIcon.className === THEME_TO_ICON_CLASS.dark) {
|
||||
setTheme('light');
|
||||
} else if (toggleIcon.className === THEME_TO_ICON_CLASS.light) {
|
||||
setTheme('dark');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -32,15 +37,8 @@ window.addEventListener('scroll', () => {
|
||||
});
|
||||
|
||||
function setTheme(themeToSet) {
|
||||
|
||||
const darkThemeCss = document.getElementById("dark-theme");
|
||||
localStorage.setItem(THEME_PREF_STORAGE_KEY, themeToSet);
|
||||
if (themeToSet === GOKARNA_DARK_THEME) {
|
||||
darkThemeCss.disabled = false;
|
||||
toggleIcon.className = "fa fa-sun-o";
|
||||
} else if(themeToSet === GOKARNA_LIGHT_THEME) {
|
||||
darkThemeCss.disabled = true;
|
||||
toggleIcon.className = "fa fa-moon-o";
|
||||
}
|
||||
darkThemeCss.disabled = themeToSet === 'light';
|
||||
toggleIcon.className = THEME_TO_ICON_CLASS[themeToSet];
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user