Created
February 4, 2021 11:52
-
-
Save brianzelip/b73931458e4ba15158dd802aa7bdb0aa to your computer and use it in GitHub Desktop.
Use the modulo operator for a looping slide show
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// When making a looping slide show, here's the long way to get at what the modulo operator provides | |
if (counter < images.length - 1) { | |
counter++; | |
} else { | |
counter = 0; | |
} | |
const prevIndex = counter < 1 ? images.length - 1 : counter - 1; | |
const currIndex = counter; | |
const nextIndex = counter == images.length - 1 ? 0 : counter + 1; | |
// Modulo | |
const prevIndex = (counter - 1 + images.length) % images.length) | |
const nextIndex = (counter + 1) % images.length; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment