How can I make this work - Multiple Modal boxes

I am working with the code here:

I have it doing (mostly) what I need, however I can only get it to run a single instance on a page. I need multiple modal elements on the same page and I can not seem to get it to work!

Any help appreciated,


How would you trigger the other modal box when the first modal box is designed to prevent other interactions on the page?

Hi @markosjal, the example on that page uses the element ID of the image to attach the lightbox behaviour, and as IDs must be unique you’d have use classes or data-attributes instead (and you should also move those style rules to an actual CSS file; moreover, you shouldn’t use IDs for styling eiter as it increases the specifity to a degree that is rarely desired):

<img class="awsm-img" data-awsm-img src="img_snow.jpg" alt="Snow">
<img class="awsm-img" data-awsm-img src="img_wire.jpg" alt="Wire">

I’d prefer data-attributes here, or alternatively dedicated js-* classes so as to separate the styling from the behaviour. Either way you can then iterate over those images to add click event listeners like so:

var images = document.querySelectorAll('[data-awsm-img]');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");

images.forEach(function (image) {
  image.addEventListener('click', function () { = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;

BTW you should also avoid setting onclick directly as this will replace previously assigned callbacks; better always add event listeners with the same-named method.

TBH I’d suggest to look for more contemporary learning sources… that w3schools project is certainly ambitious, but unfortunately many of their pages are quite dated especially as far as best practices are concerned. IMHO the no. 1 to check out for both tutorials and API reference is always the croudsourced MDN, which is way more up to date and way more extensive.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.