Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@patrickroberts patrickroberts commented Mar 30, 2020

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
You can’t perform that action at this time.