How to setup website Dark Mode
Sun, 21 Jan 2024
Ever noticed those sleek websites that let you switch to a cool dark color scheme?
That's Dark Mode, and it's not just about looks – it's about making your website easy on the eyes, especially when the lights are low.
In this blog post, we're going to keep things simple and show you how to add Dark Mode to your website.
No tech jargon, just easy steps to make your site look stylish and provide a comfy browsing experience for your visitors.
Let's dive in and make your website shine, even in the dark! 🌙✨
Let's get started!
First of all we need to choose some icons for our two states: Dark Mode On/Off
I used Moon and Sun
from icons.getbootstrap.com.
We need to position them in our html and maybe wrap them in a span:
<span><img src="/img/moon.svg"></span>
<span><img src="/img/sun.svg"></span>
Now we need to make the interaction using Javascript:
<span onclick="toggle_darkmode()"><img src="/img/moon.svg"></span>
<span onclick="toggle_darkmode()"><img src="/img/sun.svg"></span>
Next we need to define the CSS that would be toggled. To implement the Dark Mode with minimal effort we are going to use a filter (style.css):
.darkmode {
filter: invert(100%);
background-color: #DDD;
}
The last thing is to define what the toggle_darkmode function does:
<script type="text/javascript">
function toggle_darkmode () {
if (document.body.classList.contains('darkmode')) {
document.body.classList.remove('darkmode')
} else {
document.body.classList.add('darkmode')
}
}
</script>
That's all! Pretty cool huh? This site also has it implemented. Check it out in the navbar on top ^^.
You can also add persistence using cookies.
Categories: javascript, how-to