Skip to content

Instantly share code, notes, and snippets.

@andrii-marushchak
Created January 5, 2025 17:42
Show Gist options
  • Save andrii-marushchak/e8f227721cf07d29c8bc1d15d9f95e1e to your computer and use it in GitHub Desktop.
Save andrii-marushchak/e8f227721cf07d29c8bc1d15d9f95e1e to your computer and use it in GitHub Desktop.
dark-mode.js
window.siteColorScheme = siteColorScheme = getColorScheme()
function getColorScheme() {
if (localStorage.getItem('color-scheme'))
return localStorage.getItem('color-scheme')
else
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
function setColorScheme(colorScheme = window.siteColorScheme) {
localStorage.setItem('color-scheme', colorScheme)
document.querySelector('html').setAttribute('data-color-scheme', colorScheme)
}
// Set Color Scheme on Load
document.addEventListener('DOMContentLoaded', function () {
setColorScheme();
// Enable transition for Color Scheme Toggle buttons
document.documentElement.querySelectorAll('.color-scheme-toggle').forEach((btn) => {
setTimeout(() => {
btn.classList.remove('disable-transition')
}, 200)
})
})
// now this script can find and listen for clicks on the control
document.documentElement.querySelectorAll('.color-scheme-toggle').forEach((btn) => {
btn.addEventListener('click', function () {
// Flip Current Theme
window.siteColorScheme = window.siteColorScheme === 'light' ? 'dark' : 'light'
setColorScheme()
btn.setAttribute('data-color-scheme', window.siteColorScheme)
document.querySelector('html').classList.add('disable-transition')
setTimeout(() => {
document.querySelector('html').classList.remove('disable-transition')
}, 200)
})
})
// Dark Theme
[data-color-scheme="dark"] {
&:root {
--color-background: #212121;
--logo-color: #fff;
--color-text: #fff;
--color-black: rgb(26, 26, 26);
--color-grey: #878587;
--color-orange: #FF5B27;
--color-white: #fff;
}
}
// Light Theme
:root {
--color-background: #fff;
--logo-color: rgb(26, 26, 26);
--color-text: rgb(26, 26, 26);
--color-black: rgb(26, 26, 26);
--color-grey: rgb(120, 120, 120);
--color-orange: #FF5B27;
--color-white: #fff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment