I've got a full page lightbox with a slideshow gallery and I am trying to refactor my code so I will not have to use a global variable. I'm straggling with passing a variable as a parameter from function to function. It all works well when I open the lightbox gallery: the correct image is seen and the number in the counter is shown. The problem starts when I want to switch to next or previous image. I can't access the variable which stores or stored the current image seen when the lightbox was open. I'm posting my simplified code without variables' declarations.
// This is a function which opens the lightbox with the galery after clicking on a thumbnail image.
function openSlideshowLightbox (event, currentSlide) {
for (const [currentThumbnailImg] of thumbnailImgs.entries()) {
if (event.target === thumbnailImgs[currentThumbnailImg]) {
showCurrentSlide(currentSlide = currentThumbnailImg)
}
}
}
// This function shows the current slide containing an image
function showCurrentSlide (currentSlide) {
for (const slide of slides) {
if (slide.classList.contains('slide_visible')) {
slide.classList.remove('slide_visible')
slide.classList.add('slide_hidden')
} else {
slide.classList.add('slide_hidden')
}
}
slides[currentSlide].classList.remove('slide_hidden')
slides[currentSlide].classList.add('slide_visible')
}
All above is one action, the lightbox gets open and the functions finish their tasks.
Now I want to switch to next or previous image but I don't have access to currentSlide variable anymore which I need in the below function.
function navigateSlideshowLightbox (event, currentSlide) {
if (previousImgIconClicked) {
currentSlide = (currentSlide - 1 + allSlides) % allSlides
showCurrentSlide(currentSlide)
} else if (nextImgIconClicked) {
currentSlide = (currentSlide + 1) % allSlides
showCurrentSlide(currentSlide)
}
}
I tried to use return statement in showCurrentSlide():
return currentSlide
and then in navigateSlideshowLightbox():
currentSlide = showCurrentSlide()
but currentSlide is undefiend.
currentSlideas a parameter inside your functions, any global variables you have namedcurrentSlidewill not be recognized within those functions, nor will settingcurrentSlidehave any effect on the global variable.