Code snippet: Iterate slideshow counter without if/else statements

While scripting a jQuery slideshow gallery, I thought of a way of iterating the counter without needing to use an if/else statement to hard reset it to 0 when it reaches the end of the array. Then do something similar to step from the last slide back to 0. Nothing fancy with this snippet at all, you can tweak it for use in any programming languages.

Here’s the code:

var currSlide = 0; // this is the counter to track the current slide
var SlideshowLength = 5; // this determines the length of the slideshow array

function gotoNextSlide(this) { // call this function to advance slide
	currSlide++;
	currSlide%=slideshowLength; // Taking the remainder of the length automatically "resets" numbers greater than Length - 1 back into range

	/* Do slide transition stuff */
}

function gotoPrevSlide(this) { // call this function to advance slide
	currSlide = currSlide + slideshowLength - 1; // Takes the counter up one less than the multiple of the current slide number.
	currSlide%=slideshowLength; // Taking the remainder of the length automatically "resets" numbers greater than Length - 1 back into range.
	// If currSlide = 0, 0+5-1= 4, 4%5 = 4; If currSlide = 4, 4+5-1= 8 , 8%5 = 3

	/* Do slide transition stuff */
}

2 Responses

  1. Cheryl says:

    Slide transition animation going from one slide to another. Do they fade in and out or swipe left to right etc.

  2. phobik says:

    What’s the slide transition stuff? :)

Leave a Reply