HEXO Theme and font switcher

And they said it couldn’t be done 😎

This snippet switches between color schemes, and (in the article view) between font families. Try it now, it’s right up there ↗️
The theme itself uses JQuery, so we might as well.
So yeah, if your need this in your Hexo theme, here’s the scuttlebut:

_config.yml

1
2
3
4
5
6
7
8
colorscheme: light

# ...

nav:
home: /
Dark 🌑: "#theme-switcher"
Serif: "#font-switcher"

themes/[theme]/source/js/main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
function setTheme(theme) {
let selectors = 'h2, .h2, h3, .h3, .content p, .toc-item, .pagination span';
if (theme === 'dark') {
$('.highlight').css({'background-color': '#111', 'color': '#999'});
$('.highlight .name').css('color', '#7c7');
$('.highlight .string').css('color', '#cc7');
$(selectors).css('color', '#999');
$('body').css({'background-color': '#333', 'color': '#ccc'});
} else if (theme === 'light') {
$('body').css({'background-color': '#eee', 'color': '#222'});
$(selectors).css('color', '#222');
}
}

function setFont(font) {
const fontValue = font === 'serif' ? 'Serif' : 'Sans-serif';
$('.post p, .post p a, article ol, article ul').css('font-family', fontValue);
}

const storedTheme = localStorage.theme || 'light';
const storedFont = localStorage.font || 'sans';

setTheme(storedTheme);
setFont(storedFont);

$('a[href="#theme-switcher"]').text(storedTheme === 'dark' ? 'Light ☀️' : 'Dark 🌖');
$('a[href="#font-switcher"]').text(storedFont === 'serif' ? 'Sans' : 'Serif');

$('a[href="#theme-switcher"]').click(function () {
const newTheme = localStorage.theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
localStorage.theme = newTheme;
$(this).text(newTheme === 'dark' ? 'Light ☀️' : 'Dark 🌖');
});

$('a[href="#font-switcher"]').click(function () {
const newFont = localStorage.font === 'sans' ? 'serif' : 'sans';
setFont(newFont);
localStorage.font = newFont;
$(this).text(newFont === 'serif' ? 'Sans' : 'Serif');
});

And yeah, no it’s not very pretty but it’s really working around existing code… And come on, It’s just my blog.