Last active
April 1, 2022 02:05
-
-
Save huynguyen93/b729b889c9924b5f41dba87f92faaade to your computer and use it in GitHub Desktop.
Simple switch theme toggle (server-side render)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"/> | |
<title>khoahuy.com</title> | |
{% set isDarkTheme = app.request.cookies.get('defaultTheme') == 'dark' %} | |
{% set cssLightUrl = 'assets/cssLight.css' %} | |
{% set cssDarkUrl = 'assets/cssDark.css' %} | |
<link | |
class="app-style" | |
rel="stylesheet" | |
href="{{ isDarkTheme ? cssDarkUrl : cssLightUrl }}" | |
data-css-light-url="{{ cssLightUrl }}" | |
data-css-dark-url="{{ cssDarkUrl }}" | |
> | |
</head> | |
<body> | |
<button class="btn" id="theme-toggler">Swich theme</button> | |
<script> | |
const themeToggler = document.getElementById('theme-toggler'); | |
if (themeToggler) { | |
function setCookie(name,value,days) { | |
var expires = ""; | |
if (days) { | |
var date = new Date(); | |
date.setTime(date.getTime() + (days*24*60*60*1000)); | |
expires = "; expires=" + date.toUTCString(); | |
} | |
document.cookie = name + "=" + (value || "") + expires + "; path=/"; | |
} | |
themeToggler.addEventListener('click', () => { | |
themeToggler.setAttribute('disabled', 'disabled'); | |
const initialStyle = document.head.querySelector('.app-style'); | |
const currentStyleUrl = initialStyle.getAttribute('href'); | |
const lightStyleUrl = initialStyle.getAttribute('data-css-light-url'); | |
const darkStyleUrl = initialStyle.getAttribute('data-css-dark-url'); | |
const shouldChangeToLightTheme = currentStyleUrl === darkStyleUrl; | |
const newStyleLink = document.createElement('link'); | |
newStyleLink.addEventListener('load', () => { | |
initialStyle.remove(); | |
themeToggler.removeAttribute('disabled'); | |
setCookie('defaultTheme', shouldChangeToLightTheme ? 'light' : 'dark', 365); | |
}); | |
newStyleLink.setAttribute('class', 'app-style'); | |
newStyleLink.setAttribute('rel', 'stylesheet'); | |
newStyleLink.setAttribute('data-css-light-url', lightStyleUrl); | |
newStyleLink.setAttribute('data-css-dark-url', darkStyleUrl); | |
newStyleLink.setAttribute('href', shouldChangeToLightTheme ? lightStyleUrl : darkStyleUrl); | |
document.head.insertAdjacentElement('beforeend', newStyleLink); | |
}); | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment