Skip to content
Advertisement

Add a darkmode to your site via JavaScript

I’m a beginner and I set myself a challenge: create a darkmode for my portfolio with JS functions.

HTML :

JavaScript

JAVASCRIPT:

JavaScript

But I have a problem. I use “if…esle”.

The “if” part works. But the “else” part doesn’t work.

Normally, if the user has already clicked on the darkmode button, my #navbar doesn’t contain the “dark-mode” class but “.light-mode”. So the “else” part should run.

Advertisement

Answer

You’re running this function once (presumably when the page is loaded), which will evaluate the condition once and register a single event listener (either the one that sets the class to dark mode, or the one that sets it to light mode). As such, clicks will do the same thing for the entirety.

Instead you should move your if-else check inside the event listener, such that you’re checking the classes at the time of the click. This can be as simple as inverting the third and fourth lines of your function, e.g.:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement