Skip to content

Instantly share code, notes, and snippets.

@xPaw
Created October 15, 2019 07:46
Show Gist options
  • Save xPaw/eaef57f0dacc48f4ea123f894cdd34bc to your computer and use it in GitHub Desktop.
Save xPaw/eaef57f0dacc48f4ea123f894cdd34bc to your computer and use it in GitHub Desktop.
( 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