Created
March 6, 2011 07:46
-
-
Save eltiare/857123 to your computer and use it in GitHub Desktop.
An easy way to rotate images in a slideshow via jQuery
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
<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> | |
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. :)
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).
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
Very nice! But your use of ++ can go to the next level. Delete line 19, and change line 20 to read:
However, in the case of a rotating counter, I would actually replace lines 19-22 with: