I recently added a dark theme to this blog, it's great for night time reading on your laptop, tablet or phone. This is the first time I've implemented dynamic theming on a site and it was super simple to integrate. I thought I would share my thoughts and the implementation strategies I used.
Integration
The first thing I did was add a class to my body tag, in my case the class name was dark. Using Sass or Less will make the following a lot easier although it's doable with plain css.
Basically what you want to do is create a new body.theme-name definition in your stylesheet and using scss I was able to nest the rest of my styles underneath this.
body.dark {
a {
color:lighten($main-color, 20%);
}
background-color:#111;
color:#ddd;
/* rest of your styles you want to override */
}
After I got everything looking how I wanted I removed the class from the body since I didn't want this to be the default. The idea here is dynamically add the class to the body when the user wants to switch the theme. I also wanted to be able to remember the user's choice so on subsequent page loads it would load the correct theme. This is easy enough with jQuery and the jQuery cookie plugin.
$('.change-theme').on 'click', ->
if $('body').hasClass('dark')
$.cookie('dark_mode', 'false')
else
$.cookie('dark_mode', 'true')
$('body').toggleClass('dark')
The above code listens for a click on my change theme button. If the body already has a class name of dark I then set a cookie with the user's preference and toggle the theme. I do the opposite if the body doesn't have the class name.
I now needed a way to load the theme depending on the user's preference that was in the cookie. Again this is quite easy to do.
if $.cookie('dark_mode') is 'true'
$('body').addClass('dark')
I'm sure there are some jQuery plugins out there that do this for you already but it's easy enough to roll your own and it gives you more control over the implementation. I hope you enjoyed this post and if you have any questions or suggestions on how to improve this implementation leave a comment below.