Skip to content

Instantly share code, notes, and snippets.

@eltiare
Created March 6, 2011 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eltiare/857123 to your computer and use it in GitHub Desktop.
Save eltiare/857123 to your computer and use it in GitHub Desktop.
An easy way to rotate images in a slideshow via jQuery
<html>
<head>
<title>Simple Slideshow</title>
<style type='text/css'>
#slideshow { position: relative; }
#slideshow img { position: absolute; top: 0; left: 0; }
</style>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var image_counter = -1;
$(window).load(function() {
rotate_images();
setInterval(rotate_images, 7000);
});
function rotate_images() {
var images = $('#slideshow img');
image_counter = ++image_counter % images.length;
images.each(function(i, img) {
if (i == image_counter) {
$(img).css({zIndex : 4});
$(img).animate({ opacity : 1 }, 2000).animate({ zIndex : 5}, 200);
} else {
$(img).animate({ opacity : 0 }, 2000).animate({ zIndex : 0}, 200);
}
});
}
</script>
</head>
<body>
<div id="slideshow">
<img src="image1.jpg" alt="">
<img src="image2.jpg" alt="">
<img src="image3.jpg" alt="">
<img src="image4.jpg" alt="">
</div>
</body>
</html>
@dbrady
Copy link

dbrady commented Mar 6, 2011

Very nice! But your use of ++ can go to the next level. Delete line 19, and change line 20 to read:

if (image_counter++ >= images.length) {
  image_counter = 0;
}

However, in the case of a rotating counter, I would actually replace lines 19-22 with:

image_counter = ++image_counter % images.length;

@eltiare
Copy link
Author

eltiare commented Mar 6, 2011

Thanks for the input! The first suggestion I will implement. My only concern with the second one is the edge case of someone leaving the browser open for a very long time. I have a slight issue with cases where the counter goes on to infinity.

I believe you mixed up the ++ operator, though on the first one: it needs to go before. :)

@dbrady
Copy link

dbrady commented Mar 6, 2011

Ah, good spot. The second case, however, won't go to infinity. The x = x % y patterns assigns back to x in every loop, so image_counter will always stay inside [0..image_counter).

@eltiare
Copy link
Author

eltiare commented Mar 6, 2011

Haha! My turn to miss something. Very good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment