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.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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.