Loop and Animate Elements of an Array using jQuery

I stumbled across a recent thread where a user wanted to loop through an Array using jQuery and show the display the elements similar to a slide show. He wanted to avoid using the for loop and wanted to do it jQuery style. Here’s how to use the $.each() to achieve this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Loop through an array using jQuery</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
var
arrNames = ['Tom', 'Jane', 'Harry', 'Rick', 'Moby'];

$.each(arrNames, function(i, val) {
setTimeout(function() {
$('#divDisp').fadeOut("slow", function() {
$(this).text(val).fadeIn("slow");
});
}, i * 3000);
});
</script>
</
head>
<
body>
<
div id='divDisp'></div>
</
body>
</
html>

You can see a Live Demo.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Brian Jørgensen said...

Maybe this could be useful. Thank you. :-)

Anonymous said...

This is really a good / simple code to work with. I want to know how can i use this as recursive function. I mean how can we move text again & again.

Please help.