Last active
April 27, 2022 10:12
-
-
Save jairusjoer/e81543dde287a80f1349699fb78c36ca to your computer and use it in GitHub Desktop.
Simple dark mode switch with callback and local storage capability
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
/** | |
* @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