I have built a lightbox functionality in JavaScript, and I'm now working to get the implementation working when having multiple galleries at the same page, a feature I didn't take into account when developing it.
To achieve the desired effect, I'm using dataset and data-*-attributes extensively (data-index
to index, data-total
to store how many images are in the .gallery
and data-current
to store which .gallery
that should be displayed in the #lightbox
. The .gallery
with thumbnail <img>
s are wrapped in <figure><a>
with a href
attribute to the bigger #lightbox img
.
These attributes work theoretically, and return the correct values with accompanying code. After page load, when clicking on one of the galleries, the gallery works as expected, being isolated from the others, looping through the gallery images.
The problem arise when closing the lightbox, and clicking on one of the other galleries. In IE 11, I get a Unable to get value of...
error in the developer tools on the last document.querySelector
line. When outputting the returned values to console.log()
, however, I can't understand why it isn't adding the .current
class used to show the , because when values are correct and looks like a valid selector (and it still works in the first-clicked .gallery
):
This is a heavily shortened version of the JS code. Variables and selectors have also been translated into English so that people here could understand it better. Take an extra good look at the galleryindex
, galleryindexarray
, thisgallery
, thisgallerya
and current
variables, which is where the functionality around the problem lays.
var lightbox = document.createElement('div'),
gallerya = document.querySelectorAll(".gallery a"),
current, img, i, galleryindexarr = [];
for (i = 0; i < gallerya.length; i++) {
gallerya[i].addEventListener("click", function(e) {
e.preventDefault();
var galleryindex = this.parentNode.parentNode.dataset.index,
thisgallery = document.querySelector(".gallery[data-index='" + galleryindex + "']"),
thisgallerya = document.querySelectorAll(".gallery[data-index='" + galleryindex + "'] a");
if(!document.getElementById("lightbox")) {
lightbox.id = "lightbox";
document.body.insertBefore(lightbox, document.body.firstChild);
}
if(galleryindexarr.indexOf(galleryindex) == -1) {
galleryindexarr.push(galleryindex);
for (i = 0; i < thisgallerya.length; i++) {
img = document.createElement("img");
img.src = thisgallerya[i].href;
img.dataset.index = galleryindex;
lightbox.appendChild(img);
}
}
current = [].indexOf.call(thisgallery.childNodes, this.parentNode);
document.querySelector("#lightbox img[data-index='" + galleryindex + "']:nth-of-type(" + current + ")").classList.add("current");
});
}
Here is a test demo site with further visual clarification. Please assist me on this rather small error if you know anything that could help.