Okay.. There is a little bit of CSS involved?, but it was much easier then the answers I found on the internet.
What I am Trying To Achieve?
I am trying to achieve two things with this method.
So we will have a website that will load in the user expected theme and then allow them to change it when they want to.
Step 1: Create Button for toggling
1 |
|
I am using an image as my button that has a svg image of a moon. You can add your button or checkbox that feels okay for you to toggle between two options.
Step 2: Put your color details in CSS as custom properties
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Okay.. So in the root you are seeing property called color-scheme and this going to be our game changer.
As you can see, it takes values light or dark to it. I have also created two classes that .light and .dark that sets the value of color-scheme to dark or light.
Step 3: Add colors to various parts of your code
1 2 3 |
|
Now whenever a property asks for a color(like background, color properties), you can use the function called light-dark().
This function takes two values, the first one is used when color-scheme is set to light and the second one is used when color-scheme is set to dark.
Yes... This is a function that is released in May 2024. It is fairly new, but It will be adapted soon. And it is in baseline support as of writing this article. Here is the docs for it
If you use this, the CSS will automatically detect the user preference from the OS and sets it to the color they want.
We achieved our first goal, the website will load with color mode user already wanted in their OS.
Step 4: Use Javascript to toggle between dark and light mode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
Here, document.documentElement.style.colorScheme actually refers to the :root element from CSS.
As we already achieved to open the website in user preferred mode in the previous step,here when the toggle button is clicked it does the following jobs.
*PS: * This is my first post and I am still a beginner to web developing. But when I searched for this method, I have not seen any related posts about it. If you already know this, I am sorry for click baiting you?. I thought this post will help me to remember this process every time I am working on a new project.
If you are working for your website to work on old browsers, this method is definitely not for you. Tell me in the comments about this post. Thanks for reading.
The above is the detailed content of Change Light and Dark theme in just lines of JavaScript. For more information, please follow other related articles on the PHP Chinese website!