Skip to content

Instantly share code, notes, and snippets.

@sampotts
Last active June 1, 2023 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sampotts/4b388d2764f6a2a249a132a4cd9390ed to your computer and use it in GitHub Desktop.
Save sampotts/4b388d2764f6a2a249a132a4cd9390ed to your computer and use it in GitHub Desktop.
A user script to toggle Reddit's dark mode automatically based on your system preferences
// Get the initial state
const query = window.matchMedia('(prefers-color-scheme: dark)');
function toggleDarkMode(toggle = query.matches) {
// Open the menu
document.querySelector('#USER_DROPDOWN_ID[aria-expanded="false"]')?.click();
// Get the wrapper item
const wrapper = Array.from(document.querySelectorAll('button')).find(({ innerText }) => innerText.toLowerCase() === 'dark mode');
const checkbox = wrapper?.querySelector(`[aria-checked="${!toggle}"]`);
checkbox?.click();
// Close the menu
document.querySelector('#USER_DROPDOWN_ID[aria-expanded="true"]')?.click();
}
// Listen for changes
query.addEventListener('change', (event) => toggleDarkMode(event.matches));
// Run when DOM parsed with a delay for React rendering
document.addEventListener("DOMContentLoaded", () => {
setTimeout(() => toggleDarkMode(), 200);
});
// Run when visibility changes (e.g. switching tabs)
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
toggleDarkMode();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment