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:
2
src/index.d.ts
vendored
2
src/index.d.ts
vendored
@@ -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;
|
||||
|
13
src/index.js
13
src/index.js
@@ -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:
|
||||
|
Reference in New Issue
Block a user