1
mirror of https://github.com/jakejarvis/dark-mode.git synced 2025-09-11 08:28:47 -04:00

add onInit and onChange callback function options

This commit is contained in:
2021-08-05 07:54:47 -04:00
parent 8b40221791
commit cfa1f575e3
6 changed files with 53 additions and 38 deletions

2
src/index.d.ts vendored
View File

@@ -3,4 +3,6 @@ export function init(options?: {
classes?: { dark: string, light: string };
default?: string;
storageKey?: string;
onInit?: (toggle?: HTMLElement) => void;
onChange?: (theme?: string, toggle?: HTMLElement) => void;
}): void;

View File

@@ -31,6 +31,11 @@ const init = function (options) {
if (storageAvailable && !!remember) {
localStorage.setItem(storageKey, theme);
}
// optional onChange callback function passed as option
if (typeof options.onChange === "function") {
options.onChange(theme, toggle);
}
};
// user has never clicked the button, so go by their OS preference until/if they do so
@@ -72,9 +77,6 @@ const init = function (options) {
// don't freak out if page happens not to have a toggle
if (toggle !== null) {
// toggle re-appears now that we know user has JS enabled
toggle.style.visibility = "visible";
// handle toggle click
toggle.addEventListener("click", function () {
// switch to the opposite theme & save preference in local storage
@@ -85,6 +87,11 @@ const init = function (options) {
}
});
}
// optional onInit callback function passed as option
if (typeof options.onInit === "function") {
options.onInit(toggle);
}
};
// recommended method (by MDN) to detect localStorage availability: