Night Mode Toggle Across the Website!
Changing background color to a darker one helps reading under low light. This can be achieved easily with JS. But making it to remember the change across the site is a little tricky. Here is a way to do it.
I’m not proud of using a smartphone to read articles on the bed. But this is a habit many people have. Reading in low light is bad for your eyes if the phone emits a lot of bright light.
There are apps that you can use to reduce the light. A better option is to have a dark theme. Reddit already has this option. Maybe they’re aware of their being nocturnal!
How to create a dark mode?
But this seemed very easy and I gave it a try to write something on my own which was a horrible code.
Copy the code, save as HTML file and open in a browser to see how this works. It is pretty much like the below box.
This one works as expected. But I tell you this wasn’t easy. First thing is that the JS recognized only RGB code and not HEX. It took me a while to figure that out. It switches background color inline only. Also if you refresh the browser, background color goes back to default.
Store value across the domain
The problem with this approach is that it is specific to a page. If you switch the theme to dark and navigate to another page in the same domain then it will go back to its normal light theme.
We want it to remember the last switch and keep it across the domain. So if a user switches the theme once then it should remain switched unless he restarts the browser.
Using cookies is one option but it is so yesterday. Europeans know the headache of using cookies on a website.
A better way is to use either
sessionStorage. HTML5 has these options to store up to 5MB of data until you close the browser(sessionStorage) or clear the cache(localStorage).
After searching through StackOverflow and MDN, I came up with a working code.
sessionStorage to switch theme
Here is the same box which not only switches its color but also retains it even if you refresh the page!
Try navigating to some other page and come back. This box will still be dark!
This uses sessionStorage. If you close the browser and open this link again, you’ll see that the box goes back to default background.
I have used this in my new theme Hagura.
Here is the code I have used to make this happen.
1. It needs to be simple. If you observe the code, there is a lot of repetitive values which can be minimized.
It should not refresh. The changed color will not apply unless the page is refreshed. This is an inconvenience. I hope this can be solved by someone who knows JS.
I figured it out. Now the color switches without refresh!
Though it isn’t perfect yet, I think it can be used to implement theme switching or any other change that is supposed to happen across the website.
Let me know if you have successfully implemented this on your website.
Thanks for reading!