Dark Mode
Dark Mode seems to be here to stay. Initially, manly used by developers in their code editors, but now it’s all over the place, from mobile, desktops, and now even the web. Supporting Dark Mode is more and more turning from a nice to have, to a must-have. Of course, depending on your niche, but if you are here, chances are, you want to implement Dark Mode on your site or for your clients.When it comes to dark mode for websites there are multiple approaches on the web.
Using JS and CSS
The first work is by the use of “dark” magic :p, joke aside, it’s very simple and elegant, and consists of really one line of CSS.html { } html[data-theme='dark'] { background: #000; filter: invert(1) hue-rotate(180deg) }What? You are probably wondering how that could work, and you may be right to be skeptical, but it does indeed. Let’s see it in action before we talk about why I don’t like this option so much:
This is the html script
<html> <body> <h1>Hello World</h1> <h2>Welcome to my Dark Mode Test</h2> <p> Here is some text to convert to dark mode </p> <img alt="test" src="https://trednix.com/featured.png" width="100px" /> <br /> <button onclick="toggleTheme('dark');">Dark</button> <button onclick="toggleTheme('light');">Light Mode</button> </body>The CSS script has been given above.
Now let's give the js scripts:
const htmlEl = document.getElementsByTagName('html')[0]; const toggleTheme = (theme) => { htmlEl.dataset.theme = theme; }Now everything works smoothly and really nice but if you reload the page,it would return to its initial ,which was the light mode , we want it to be dynamic and to do so,js got us covered.we also want to make sure our changes are stored on the browser so that we remember the user preference for the next time he/she visits our site. For that we will use the localStorage API.
// Capture the current theme from local storage and adjust the page to use the current theme. const htmlEl = document.getElementsByTagName('html')[0]; const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null; if (currentTheme) { htmlEl.dataset.theme = currentTheme; } // When the user changes the theme, we need to save the new value on local storage const toggleTheme = (theme) => { htmlEl.dataset.theme = theme; localStorage.setItem('theme', theme); }You can also learn how to create a beautiful search engine
Comments
Post a Comment