Skip to content
Advertisement

Slideshow / Carousel not working properly in a specific condition?

This JS code is not working properly. What is the reason ?

let indexOfSlide = 1; // update me !
show(indexOfSlide);

function liveSlide(n){
   show(indexOfSlide = n); // update me !
}

function plusSlidesItem(n){
   show(indexOfSlide += n);
}

function show(indexOfSlide) {
    let slides_item = document.getElementsByClassName("slides-item");
    let tiny_img = document.getElementsByClassName("tiny-img");
    let i;
    
    if( indexOfSlide < 1){
        indexOfSlide = slides_item.length;
    }
    if( indexOfSlide > slides_item.length){
        indexOfSlide = 1;
    }

    for(i=0;i<slides_item.length;i++){
        slides_item[i].style.display = "none";
    }

    for(i=0;i< slides_item.length; i++){
        tiny_img[i].style.opacity = "0.5";
    }

    slides_item[indexOfSlide-1].style.display = "initial";
    tiny_img[indexOfSlide-1].style.opacity = "1" ;
}

When indexOfSlide is replaced by n in show() function’s argument and in two if statements condition in show() then it works properly. Why ?

Advertisement

Answer

There are a few code refactoring that could be done here.

let indexOfSlide = 1; // update me !

// we might as well use the global variable indexOfSlide instead of
// passing it as a parameter since it is updating at each call
function show() {
    let slides_item = document.getElementsByClassName("slides-item");
    let tiny_img = document.getElementsByClassName("tiny-img");

    if( indexOfSlide < 1 ){
        indexOfSlide = slides_item.length;
    } else if( indexOfSlide > slides_item.length ){
        indexOfSlide = 1;
    }

    // you can merge both the loops since they are
    // iterating over the same index sequence
    for(let i = 0; i < slides_item.length; i++){
        slides_item[i].style.display = "none";
        tiny_img[i].style.opacity = "0.5";
    }

    slides_item[indexOfSlide - 1].style.display = "initial";
    tiny_img[indexOfSlide - 1].style.opacity = "1" ;
}

// calling the show() function after it has been defined
// is how it should be done else it'll throw an error

show();

function liveSlide(n){
   indexOfSlide = n;
   show(); // update me !
}

function plusSlidesItem(n){
   indexOfSlide += n;
   show();
}

see if it fixes the problem

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement