Created
March 30, 2020 22:26
-
-
Save patrickroberts/b0c62bddd710f3a3dca5f1d2cadfd678 to your computer and use it in GitHub Desktop.
Dark Mode Toggle in Menu Header
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
// ==UserScript== | |
// @name Stack Overflow Theme Toggle | |
// @version 0.1 | |
// @description Shortcut for Dark Mode on Stack Overflow | |
// @author Patrick Roberts | |
// @match https://stackoverflow.com/* | |
// @grant none | |
// ==/UserScript== | |
$(function() { | |
var $body = $('body'); | |
var symbols = ['🌞', '🌙']; | |
function theme() { | |
return ( | |
$body.hasClass('theme-system') | |
? +window.matchMedia('(prefers-color-scheme: dark)').matches | |
: +$body.hasClass('theme-dark') | |
); | |
} | |
var $toggle = $('<a>') | |
.addClass('-link') | |
.text(symbols[1 - theme()]) | |
.on('click', function() { | |
var user = StackExchange.options.user; | |
$.post('/account/set-theme-preference', { fkey: user.fkey, accountId: user.accountId, theme: 1 - theme() }) | |
.done(function (response) { | |
$body | |
.removeClass(function (i, oldClassList) { | |
return (oldClassList.match(/(^|\s)theme-\S+/g) || []).join(' '); | |
}) | |
.addClass(response.themeClass || ''); | |
$toggle.text(symbols[1 - theme()]); | |
}) | |
.fail(function (response) { | |
var error = JSON.parse(response.responseText).ErrorMessage; | |
StackExchange.helpers.showToast(error, { type: 'danger' }); | |
}); | |
}) | |
.appendTo($('<li>') | |
.addClass('-item') | |
.insertAfter('.site-switcher-item')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's what the toggle looks like: