From e560cba627b2391ce1249ca7de158646fabdea85 Mon Sep 17 00:00:00 2001 From: Eltrac Date: Mon, 15 Sep 2025 12:00:28 +0800 Subject: refactor: click overlay to dismiss --- src/lightbox.js | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/lightbox.js b/src/lightbox.js index 57922b3..1a93a53 100644 --- a/src/lightbox.js +++ b/src/lightbox.js @@ -2,7 +2,6 @@ import Overlay from './overlay.js'; import Shadow from './shadow.js'; export default class LightBox { - overlay = new Overlay(); shadows = {}; /** @@ -13,13 +12,20 @@ export default class LightBox { constructor({ container }) { this.container = container; - this.init(); + this.initOverlay(); + this.initImages(); } - init() { - const images = document.querySelectorAll(`${this.container} img[data-libo]`); + initOverlay() { + this.overlay = new Overlay(); + this.overlay.element.addEventListener('click', e => { + this.closeAll(); + }); + } - images.forEach(image => { + initImages() { + this.images = document.querySelectorAll(`${this.container} img[data-libo]`); + this.images.forEach(image => { image.id = crypto.randomUUID(); // generate unique id for image const link = this.wrapInLink(image); // add event listener to open lightbox on click @@ -58,9 +64,6 @@ export default class LightBox { const shadow = this.shadows[image.id] || new Shadow(image); if (!this.shadows[image.id]) { this.shadows[image.id] = shadow; - shadow.element.addEventListener('click', () => { - if (shadow.isOpen) this.closeLightBox(image); - }); } shadow.open(); @@ -77,4 +80,11 @@ export default class LightBox { shadow.close(); this.overlay.hide(); } + + closeAll() { + this.images.forEach(image => { + this.closeLightBox(image); + }); + this.overlay.hide(); + } } -- cgit v1.2.3