Skip to content

Instantly share code, notes, and snippets.

@patrickroberts
Created March 30, 2020 22:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickroberts/b0c62bddd710f3a3dca5f1d2cadfd678 to your computer and use it in GitHub Desktop.
Save patrickroberts/b0c62bddd710f3a3dca5f1d2cadfd678 to your computer and use it in GitHub Desktop.
Dark Mode Toggle in Menu Header
// ==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'));
});
@patrickroberts
Copy link
Author

Here's what the toggle looks like:
image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment