Skip to content
Advertisement

Add button to switch between light and dark mode using two prefers-color-scheme

I have created a page with complex design and different background colors and I decided to add a button to let users switch between light and dark mode

I’ve tried different solutions with JS, but with no success. The current workaround I use is adding two media in my CSS file. Basically, if my website appearance is set to Dark, the page will also load dark-styled theme, and Light for Browser Light Appearance.

JavaScript

Question is: How can I let users manually change between dark-light color-schemes manually with a button using vanilla Javascript? (not with the checkbox) P.s. Maybe I could somehow implement this with var(–rule) in CSS but I’m still new to this stuff and I have almost zero JS knowledge

For example:

JavaScript

html button (i class/button is a placeholder)

JavaScript

Here is my button inside sticky nav which I plan to use to switch modes dark mode button inside nav bar

Advertisement

Answer

JavaScript
JavaScript
JavaScript
in my opinion: if you want to make multiple elements react to your actions you can make a common class and use it so you can change their style
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement