Skip to content

Instantly share code, notes, and snippets.

@jairusjoer
Last active April 27, 2022 10:12
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 jairusjoer/e81543dde287a80f1349699fb78c36ca to your computer and use it in GitHub Desktop.
Save jairusjoer/e81543dde287a80f1349699fb78c36ca to your computer and use it in GitHub Desktop.
Simple dark mode switch with callback and local storage capability
/**
* @param {object} night Configure night mode controls and targets.
* @param {string} night.mount Mount theme class to single given DOM element.
* @param {string} night.targets Match control targets using `querySelectorAll()`.
* @param {string} [night.theme] Set optional theme name to be mounted. Default: night.
* @param {function} [night.callback] Optional callback triggered on target interaction.
* @return {object} Current theme state and targeted DOM elements.
*/
const night = ({ mount, targets, theme = "night", callback }) => {
const _data = { mount, targets };
const _mount = document.querySelector(mount);
const _targets = document.querySelectorAll(targets);
if (localStorage.theme == theme) {
_mount.classList.add(theme);
callback({ ..._data, theme: localStorage.theme });
}
_targets.forEach((item) => {
item.onclick = () => {
_mount.classList.toggle(theme);
localStorage.theme = localStorage.theme == theme ? "default" : theme;
callback({ ..._data, theme: localStorage.theme });
return { ..._data, theme: localStorage.theme };
};
});
};
export { night };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment