Search code examples
javascriptcounterdevelopment-environmentslide

Dont figure what s the role of the counter in javascript


I want to create a fullscreen image slider in js so I watched a tutorial and I understand most of it beside the 'counter'.I know that its representing the current image but I don't know how it doing that, how is assigned.

HERE IS THE CODE

let sliderImages = document.querySelectorAll(".slide"),
    arrowLeft = document.querySelector("#arrow-left"),
    arrowRight = document.querySelector("#arrow-right"),
    current = 0; (!!!!THIS ONE I DON`T UNDERSTAND HOW IT S REPRESENTING THE CURRENT IMAGE!!!

// Clear all images
function reset() {
    for (let i = 0; i < sliderImages.length; i++) {
        sliderImages[i].style.display = "none";
    }
}

// Init slider
function startSlide() {
    reset();
    sliderImages[0].style.display = "block";
}

// Show prev
function slideLeft() {
    reset();
    sliderImages[current - 1].style.display = "block";
    current--;
}
// Left arrow click
arrowLeft.addEventListener("click", function () {
    if (current === 0) {
        current = sliderImages.length;
    }
    slideLeft();
});

// Show next
function slideRight() {
    reset();
    sliderImages[current + 1].style.display = "block";
    current++;
}


// Right arrow click
arrowRight.addEventListener("click", function () {
    if (current === sliderImages.length - 1) {
        current = -1;
    }
    slideRight();
});

startSlide();

!! HERE IS THE LINK FROM TUTORIAL https://youtu.be/7ZO2RTMNSAY


Solution

  • Current is being used for the index of the array that contains all the elements with the class name of slide.

    It might be beneficial for you to read more about arrays: https://www.w3schools.com/js/js_arrays.asp