mirror of
https://github.com/jakejarvis/dark-mode.git
synced 2025-09-11 08:19:04 -04:00
add onUserToggle callback, move onInit and onChange up
This commit is contained in:
3
src/index.d.ts
vendored
3
src/index.d.ts
vendored
@@ -4,5 +4,6 @@ export function init(options?: {
|
||||
default?: string;
|
||||
storageKey?: string;
|
||||
onInit?: (toggle?: Element | null) => unknown;
|
||||
onChange?: (theme?: string, toggle?: Element | null) => unknown;
|
||||
onUserToggle?: (toggle?: Element | null) => unknown;
|
||||
onChange?: (theme: string, toggle?: Element | null) => unknown;
|
||||
}): void;
|
||||
|
25
src/index.js
25
src/index.js
@@ -20,6 +20,11 @@ const init = function (options) {
|
||||
|
||||
// receives a class name and switches <body> to it
|
||||
const activateTheme = function (theme, remember) {
|
||||
// optional onChange callback function passed as option
|
||||
if (typeof options.onChange === "function") {
|
||||
options.onChange(theme, toggle || null);
|
||||
}
|
||||
|
||||
document.body.classList.remove(dark, light);
|
||||
document.body.classList.add(theme);
|
||||
active = theme === dark;
|
||||
@@ -27,13 +32,13 @@ const init = function (options) {
|
||||
if (remember) {
|
||||
localStorage.setItem(storageKey, theme);
|
||||
}
|
||||
|
||||
// optional onChange callback function passed as option
|
||||
if (typeof options.onChange === "function") {
|
||||
options.onChange(theme, toggle);
|
||||
}
|
||||
};
|
||||
|
||||
// optional onInit callback function passed as option
|
||||
if (typeof options.onInit === "function") {
|
||||
options.onInit(toggle || null);
|
||||
}
|
||||
|
||||
// user has never clicked the button, so go by their OS preference until/if they do so
|
||||
if (!pref) {
|
||||
// returns media query selector syntax
|
||||
@@ -75,6 +80,11 @@ const init = function (options) {
|
||||
if (toggle !== null) {
|
||||
// handle toggle click
|
||||
toggle.addEventListener("click", function () {
|
||||
// optional onUserToggle callback function passed as option
|
||||
if (typeof options.onUserToggle === "function") {
|
||||
options.onUserToggle(toggle);
|
||||
}
|
||||
|
||||
// switch to the opposite theme & save preference in local storage
|
||||
if (active) {
|
||||
activateTheme(light, true);
|
||||
@@ -83,11 +93,6 @@ const init = function (options) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// optional onInit callback function passed as option
|
||||
if (typeof options.onInit === "function") {
|
||||
options.onInit(toggle);
|
||||
}
|
||||
};
|
||||
|
||||
export { init };
|
||||
|
Reference in New Issue
Block a user