If Statement Confuses Me
I have this code here for a slider and I don't understand what if statement does.
In my head are 2 options
First, if the current === sliderImages.length - 1
then current === 1
, second, if the current === sliderImages.length - 1
then the current === 2
(the length of the array) then take away one.
Here is my (JavaScript) code:
let sliderImages = document.querySelectorAll(".slide"),
arrowLeft = document.querySelector("#arrow-left"),
arrowRight = document.querySelector("#arrow-right"),
current = 0;
// 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();
Answer
I think your problem comes from thinking about specific numbers on your array. Imagine instead you have an array with n
numbers.
if (current === sliderImages.length - 1) {
current = -1;
}
The sliderImages.length
would be n
(10 for example, or 20, any number).
Your current
variable tells you which image you're currently showing. So if you click the Right Arrow then you want to move one step to the right. But if you're on the last position of the array, the next image, would be the first image. So you do current = -1
In other words: that if is checking whether you're in the last image if so, move back to the first position on the array.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM