Last active
August 10, 2020 03:49
-
-
Save stripedpurple/59a5de5bfd002cb0fa615463e36b1da2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// ==UserScript== | |
// @name Simple Dark Mode Toggle | |
// @namespace https://stripedpurple.io | |
// @version 0.2 | |
// @description Simple dark mode toggle for all sites | |
// @author Austin Barrett | |
// @match *://*/* | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
function init() { | |
let toggled = localStorage.getItem('darkMode') == 'true' || !!localStorage.setItem('darkMode', false) | |
let html = document.querySelector('html'); | |
let themeToggle = document.createElement('div'); | |
themeToggle.setAttribute('id','theme-toggle'); | |
themeToggle.innerHTML = '<span></span>'; | |
document.body.appendChild(themeToggle); | |
if (toggled) { | |
themeToggle.classList.toggle('toggled') | |
html.setAttribute('theme', 'dark-mode'); | |
localStorage.setItem('darkMode', toggled) | |
} | |
addStyle(`html { | |
transition: color 300ms, background-color 300ms; | |
} | |
html[theme='dark-mode'] { | |
filter: invert(1) hue-rotate(180deg); | |
} | |
html[theme='dark-mode'] img{ | |
filter: invert(1) hue-rotate(180deg); | |
} | |
#theme-toggle { | |
z-index: 10000000; | |
box-sizing: border-box; | |
position: fixed; | |
top: 0; | |
width: 2rem; | |
height: 1rem; | |
border-radius: 100px; | |
border: 1px solid #333333; | |
background: #fefefe; | |
transition: all ease-in-out 0.3s; | |
} | |
#theme-toggle span{ | |
box-sizing: border-box; | |
display: block; | |
width: calc(1rem - 2px); | |
height: calc(1rem - 2px); | |
border-radius: 50%; | |
border: 1px solid #fefefe; | |
background: #333333; | |
transition: all ease-in-out 0.3s; | |
} | |
#theme-toggle.toggled span{ | |
box-sizing: border-box; | |
display: block; | |
width: calc(1rem - 2px); | |
height: calc(1rem - 2px); | |
border-radius: 50%; | |
border: 1px solid #fefefe; | |
background: #333333; | |
margin-left: auto; | |
} | |
`) | |
themeToggle.addEventListener('click', function (e) { | |
e.prevent; | |
themeToggle.classList.toggle('toggled') | |
toggled ? html.removeAttribute('theme') : html.setAttribute('theme', 'dark-mode'); | |
toggled = !toggled; | |
localStorage.setItem('darkMode', toggled) | |
}) | |
} | |
function addStyle(styleString) { | |
const style = document.createElement('style'); | |
style.textContent = styleString; | |
document.head.append(style); | |
} | |
window.onload = init | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment