Created
October 15, 2019 07:46
-
-
Save xPaw/eaef57f0dacc48f4ea123f894cdd34bc to your computer and use it in GitHub Desktop.
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
( function() | |
{ | |
const darkMode = document.getElementById( 'dark-mode-toggle' ); | |
if( darkMode ) | |
{ | |
const isDarkSchemePreferred = () => window.matchMedia && window.matchMedia( '(prefers-color-scheme: dark)' ).matches; | |
darkMode.addEventListener( 'click', function( e ) | |
{ | |
e.preventDefault(); | |
e.stopImmediatePropagation(); | |
const isDark = document.documentElement.classList.contains( 'dark-mode' ) ? 0 : 1; | |
this.href = '?dark=' + ( 1 - isDark ); | |
// If prefers-color-scheme is dark, and user disables dark mode, we need to keep the cookie as dark=0 | |
document.documentElement.classList.toggle( 'dark-mode', isDark ); | |
document.cookie = '__Host-dark=' + isDark + '; path=/; secure; samesite=lax; max-age=' + ( isDark || isDarkSchemePreferred() ? '7776000' : '0' ); | |
} ); | |
if( isDarkSchemePreferred() && document.cookie.indexOf( '__Host-dark=' ) === -1 ) | |
{ | |
darkMode.click(); | |
} | |
} | |
}( ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment