This is some code written in a course I'm busy taking on Udemy. It serves as a basic toggle switch to flip between light and dark mode. This includes the nav bar, background, images and the icon that changes from a sun to a moon.
The objective after the lesson was to clean up the code and make it DRY. I've done so to some of the code already. But there are some instances where it still repeats, for instance isDark
in my lightDarkMode
function. Is there a way to eliminate the repetitive usage of isDark
?
const toggleSwitch = document.querySelector('input[type="checkbox"]');
const nav = document.getElementById('nav');
const toggleIcon = document.getElementById('toggle-icon');
const textBox = document.getElementById('text-box');
const darkLightTheme = ['dark', 'light'];
function imageMode(color) {
image1.src = `img/undraw_proud_coder_${color}.svg`;
image2.src = `img/undraw_feeling_proud_${color}.svg`;
image3.src = `img/undraw_conceptual_idea_${color}.svg`;
}
lightDarkMode = (isDark) => {
nav.style.backgroundColor = isDark ? 'rgb(0 0 0 / 50%)' : 'rgb(255 255 255 / 50%)';
textBox.style.backgroundColor = isDark ? 'rgb(255 255 255 / 50%)' : 'rgb(0 0 0 / 50%)';
toggleIcon.children[0].textContent = isDark ? 'Dark Mode' : 'Light Mode';
isDark ? toggleIcon.children[1].classList.replace('fa-sun', 'fa-moon') : toggleIcon.children[1].classList.replace('fa-moon', 'fa-sun');
isDark ? imageMode(darkLightTheme[0]) : imageMode(darkLightTheme[1]);
}
dark
assuming light is the default so it doesn't need a class. Then just reference.dark nav{}
and.dark #text-box{}
etc in your stylesheet. That would clean up the javascript tremendously as you would be simply toggling a class on the body and then only need to deal with the images. \$\endgroup\$