summaryrefslogtreecommitdiff
path: root/src/lightbox.js
diff options
context:
space:
mode:
authorEltrac <hi@guhub.cn>2025-09-15 12:00:28 +0800
committerEltrac <hi@guhub.cn>2025-09-15 12:00:28 +0800
commite560cba627b2391ce1249ca7de158646fabdea85 (patch)
tree12cab6dddf35158dd00f4ac17dc200a3ec32ad5e /src/lightbox.js
parent1579fe74e78895a12fb898414f32babfd467f40f (diff)
refactor: click overlay to dismiss
Diffstat (limited to 'src/lightbox.js')
-rw-r--r--src/lightbox.js26
1 files changed, 18 insertions, 8 deletions
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();
+ }
}