I found a lightweight lightbox code example, however, it relies on IDs and I intend to use it on 20+ items, I’d rather not have 20 hard-coded js lines to refer to something I know can be dynamic, I’m just not skilled enough with JS to condense into something clean.
HTML:
<template id="one">
<h1>HTML <template one> Tag</h1>
<p>The template element holds HTML code without displaying it.<br>Doesn't work in older browsers.</p>
</template>
<button class="template" data-ref="one">template</button>
<template id="two">
<h1>HTML <template two> Tag</h1>
<p>The template element holds HTML code without displaying it.<br>Doesn't work in older browsers.</p>
</template>
<button class="template" data-ref="two">template two</button>
JS:
const templateInstance = basicLightbox.create(document.querySelector('#one'))
const templateInstanceTwo = basicLightbox.create(document.querySelector('#two'))
document.querySelector('button.template' + '[data-ref=one]').onclick = templateInstance.show
document.querySelector('button.template' + '[data-ref=two]').onclick = templateInstanceTwo.show
Technically this works, but is repetitive and not scalable to large n templates.
2
Answers
To DRY the logic up you can use a loop to iterate through all
button.template
elements to attach individual event handlers to them. In those event handlers you can read the value from thedata-ref
attribute and use it to instantiate the lightbox. Here’s a working example:This is another way with plain javascript, no need for a external library: