diff options
| author | Eltrac <hi@guhub.cn> | 2025-09-15 14:51:24 +0800 |
|---|---|---|
| committer | Eltrac <hi@guhub.cn> | 2025-09-15 14:51:24 +0800 |
| commit | 600a19e769d47d3c246a180d70c8002e63de7019 (patch) | |
| tree | 66735ead10aef5ede3542b2976d64a3b6d05da55 /src | |
| parent | 134316f3a6f972e19b8b2414f16bba69ddbf2c22 (diff) | |
refactor: clearer code structrue
Diffstat (limited to 'src')
| -rw-r--r-- | src/lightbox.js | 45 |
1 files changed, 24 insertions, 21 deletions
diff --git a/src/lightbox.js b/src/lightbox.js index f3aeb6f..cd657da 100644 --- a/src/lightbox.js +++ b/src/lightbox.js @@ -27,14 +27,34 @@ export default class LightBox { 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 + + function wrapInLink(image) { + // wrap image with a link if it's not already wrapped + const parent = image.parentElement; + let link; + if (!parent || parent.tagName !== 'A') { + link = document.createElement('a'); + link.href = image.src; + // replace image with the linked one + parent.insertBefore(link, image); + link.appendChild(image); + } else { + link = parent; + } + return link; + } + + function addListener(link, image) { link.addEventListener('click', e => { e.preventDefault(); this.openLightBox(image); }); + } + + this.images.forEach(image => { + image.id = crypto.randomUUID(); // generate unique id for image + const link = wrapInLink(image); + addListener(link, image); }); } @@ -51,23 +71,6 @@ export default class LightBox { }); } - wrapInLink(image) { - // wrap image with a link if it's not already wrapped - const parent = image.parentElement; - let link; - if (!parent || parent.tagName !== 'A') { - link = document.createElement('a'); - link.href = image.src; - link.dataset.liboLink = true; - - parent.insertBefore(link, image); - link.appendChild(image); - } else { - link = parent; - } - return link; - } - /** * ============ * Actions |
