Skip to content

Instantly share code, notes, and snippets.

@20k-ultra
Last active December 10, 2019 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 20k-ultra/41edc0c131ae206c9fcf9a222b19c709 to your computer and use it in GitHub Desktop.
Save 20k-ultra/41edc0c131ae206c9fcf9a222b19c709 to your computer and use it in GitHub Desktop.
Standard functions for getting/setting themes
function rememberTheme (theme) {
// Persist in sessionStorage so theme is applied
// across pages with file:/// apply remembered theme
sessionStorage.setItem('mdbook-theme', theme)
// Persist to localStorage for normal usage as well
localStorage.setItem('mdbook-theme', theme)
}
function getTheme () {
var theme
// Get remembered theme from sessionStorage first
const THEME_SESSION = sessionStorage.getItem('mdbook-theme')
if (THEME_SESSION) {
theme = THEME_SESSION
} else {
// Check localStorage
theme = localStorage.getItem('mdbook-theme')
}
if (theme) {
// Parse out quotes
if (theme.startsWith('"') && theme.endsWith('"')) {
// Remove quotes from theme
theme = theme.slice(1, theme.length - 1)
// Persist theme
sessionStorage.setItem('mdbook-theme', theme)
localStorage.setItem('mdbook-theme', theme)
}
} else {
// Use default theme
theme = default_theme
}
return theme
}
function renderTheme () {
// Look for user specified theme
try { theme = getTheme() } catch(e) { }
// Apply theme
return applyTheme(theme)
}
function applyTheme (theme) {
// Once a theme is changed make sure to persist it
rememberTheme(theme)
// Theme is applied via CSS so update the required elements
document.body.className = theme;
document.querySelector('html').className = theme + ' js';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment