From d2eb85d9ccb9bf62efb3950bec9c25572c0b3f89 Mon Sep 17 00:00:00 2001 From: Marshall Ku Date: Mon, 18 Nov 2024 23:24:54 +0900 Subject: [PATCH] Add logics for handling keyboard event Closes #5 --- src/zoom.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/zoom.ts b/src/zoom.ts index a6cc136..0ca5a3c 100644 --- a/src/zoom.ts +++ b/src/zoom.ts @@ -21,6 +21,12 @@ const zoom = (image: HTMLImageElement, { background, useMaximumSize = true, onTr const bg = document.createElement("div"); const imageClone = document.createElement("img"); + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") { + removeImage(); + } + }; + const removeImage = () => { bg.classList.remove("zoom-bg--reveal"); imageClone.style.transform = ""; @@ -37,6 +43,7 @@ const zoom = (image: HTMLImageElement, { background, useMaximumSize = true, onTr imageClone.removeEventListener("click", removeImage); window.removeEventListener("scroll", removeImage); window.removeEventListener("resize", removeImage); + document.removeEventListener("keydown", handleKeyDown); }; bg.classList.add("zoom-bg"); @@ -77,6 +84,9 @@ const zoom = (image: HTMLImageElement, { background, useMaximumSize = true, onTr once: true, passive: true, }); + document.addEventListener("keydown", handleKeyDown, { + passive: true, + }); document.body.append(bg, imageClone);