Call Honest Code at (619) 800-0116

For a project, the client had a page with lots of thumbnails, and wanted them to cascade in gracefully, but quickly. Using jQuery, I could have used a callback function at the end of each animation to move onto the next one. However, with a large (and potentially unknown) number of objects, the difficulty of doing this ranges from impractical to impossible.

I could have also queued the animation so each thumbnail appeared serially, but this took too long. (A 300ms animation repeated 40 times gets very tedious.) Instead, I wanted a way to start a 300ms fade-in animation, and start the next thumbnail animating after only 50ms. I did using the setInterval function:

boxes = $("div.box");
var z = 0;
var refreshId = setInterval(function() {
	 boxes.eq(z).animate({ opacity:1 },300);
	 z++;
	 if (z > boxes.length) {
	 	clearInterval(refreshId);
	 }
}, 50);

This works with an unknown number of thumbnails, and stops iterating after the last thumbnail is done animating. In this example, I’m only manipulating the opacity style argument. (That is to say, making this work with IE is an exercise left for the reader.) However, using another method — like .show(), for example — is easily doable too.

You can view a demo here.


Posted May 21, 2010. Tagged: ,

 

© 2018 Honest Code, LLC. We love you. Powered by WordPress.
Privacy Policy. Terms of Service.