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!
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):
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 () {
modal.style.display = "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.