Theme that web site

Set your readers free!

From the beginning, the web was designed with the notion that users should be able to choose how they see content. Not only is it still a good idea, it's more important to remember now than ever. With mobile platforms, ad blockers and plugins like Stylus, if you don't let users read the way they want, they can and will replace your design entirely!

So, it's in your interest to build in themes in the first place. Now I'll show you how easy it can be...

Try it out

At the bottom of this article (assuming you're reading it from my site, you'll see a little item to select a theme. Try it out. I currently have four themes set; the standard dark one, two dark-on-light themes (News and Victorian) and an alternative dark theme with large print. These themes are just standard CSS stylesheets which set colours and fonts, and each of those stylesheets calls the same "layout" stylesheet behind the scenes. (Probably you can find mistakes in them, but try not to get hung up on them. The theme selector is the important bit.)

How it works

It's a simple application of HTML5's local storage API, with a tiny bit of Javascript. A script hook in the selector saves the keyword from the menu (Dark, News, etc) to local storage and a bit of site-wide script at the top reads the value and inserts it into the HTML.

The menu code (cleaned up a bit):

<div class='ThemeSelector'> Select a theme: <script> function slt() { var ltheme=document.getElementById('ThemeSelector').value; window.localStorage.setItem('_local_theme',ltheme); window.location.reload(false); } </script>; <select class='Theme' id='ThemeSelector' onchange='slt()'> <option value='Dark>Dark</option> <option value='News'>News</option> <option value='Victorian'>Victorian</option> <option value='Large_Print'>Large_Print</option> </select> <script> var ltheme=window.localStorage.getItem('_local_theme'); document.getElementById('ThemeSelector').value=ltheme; </script> </div>

The relevant theme-setting code:

<link type='text/css' rel='stylesheet' id='_theme' href='/stylesheets/Dark.css' title='Dark' /> <script> var ltheme=window.localStorage.getItem('_local_theme'); if(ltheme) {document.getElementById('_theme').setAttribute('href','/stylesheets/'+ltheme+'.css');} </script>

You can list more than one stylesheet in your HTML, and the site actually does so. The important point is to make sure the "main" one has an id value (here set to "_theme") so you can set it with a script.