blog.bejarano.io

Adding themes to this blog

Today I added themes to this very blog!

You can try them out clicking on the tiny little moon [🌗] icon bottom-left of the page.

Howto

As this site is a static site hosted on S3, I had to do it statically.

To do so, I had to solve three main problems: themes, persistency and compatibility; all while keeping the beautiful efficiency of the site.

Due to the purely static nature of the HTML+CSS stack, I had to dust off my JavaScript not-even-skills.

Themes

Theming on a well designed, properly structured static site it's as easy as changing two colors: body's background and text's color.

To style everything, I defined three classes: x0, x1 and x2 for Light, Financial and Dark (you'll see why in a minute), and styled body and text accordingly.

Light

Black on white, nothing fancy. This is the original theme, the one that this blog was designed with.

Financial

Barely darker text on Financial Times pink. Easier on the eyes, especially in dark rooms.

Dark

White on black and a slightly brighter accent blue. The one theme you think about when you talk about theming.

Note: I might add a sepia/bookpage theme in the future.

Persistency

Now that's a problem.

Persistency on static sites (without server-side cookies) has it's trickery. document.cookie doesn't work on Chrome, so I had to use localStorage, which coincidentally has a theme attribute, who knew!.

I wanted persistency both, between posts and between reading sessions (say, you visit this blog once a month, I want your theme preferences to stick around as long as you don't delete your browser's localStorage).

The issues

localStorage.theme initializes as NaN, so I must check beforehand.

In order to keep the script tiny, I have three classes: x0, x1 and x2 for Light, Financial and Dark. They are numbered so that everytime you click the pi it adds up one to localStorage.theme. They have an x as prefix because I had to use some letter to have a valid class name.

Adding one indefinetly has an overflowing problem, so modulo to the rescue!. Modulo localStorage.theme over the amount of themes (3)!

Then, set document.body.className=xA, with A being the number of the theme (localStorage.theme % 3).

Then, store the theme number in localStorage.theme.

Whenever you visit the site again, it runs the script, sets document.body.className to whatever your localStorage.theme is, and styles the page!

Compatibility

localStorage.theme is a HTML standard!

I've tested it in modern Chrome, Firefox and Safari, if you find it doesn't work in your browser, let me know!

The code

This is the JavaScript portion:

Elegant!

Everything else is just CSS styling of the .x0, .x1, etc. classes and having a button like this one placed at the bottom of the page:

<p style=cursor:pointer onclick=f(++s.theme%3)>🌗</p>