Forum Moderators: open

Message Too Old, No Replies

JQuery loop / cycle

how to loop through a function

         

dwpub

4:20 pm on Feb 25, 2009 (gmt 0)

10+ Year Member



I currently have the following code, that fades in and out of 5 list items and works exactly as I want, although I must confess I am a JQuery newby and the following code could probably been done a lot cleaner.


<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function() {
$j('#title1').fadeIn(5000);
$j('#title1').fadeOut(5000, function () {
$j('#title2').fadeIn(5000);
$j('#title2').fadeOut(5000, function () {
$j('#title3').fadeIn(5000);
$j('#title3').fadeOut(5000, function () {
$j('#title4').fadeIn(5000);
$j('#title4').fadeOut(5000, function () {
$j('#title5').fadeIn(5000);
$j('#title5').fadeOut(5000);
});
});
});

});
});
</script>

What I'd like to know is how to get this to loop through indefinitely. i.e. when it fadeouts title5, it then start back at the top on title1 again and so on.

sandblocks

9:07 am on Mar 7, 2009 (gmt 0)

10+ Year Member



You are probably right that what you're trying to do could be accomplished in a better way. But to answer your question about looping the function, try this:

(Modified times to make testing faster)


function fadeTitles() {
$('#title1').fadeIn(500);
$('#title1').fadeOut(500, function () {
$('#title2').fadeIn(500);
$('#title2').fadeOut(500, function () {
$('#title3').fadeIn(500);
$('#title3').fadeOut(500, function () {
$('#title4').fadeIn(500);
$('#title4').fadeOut(500, function () {
$('#title5').fadeIn(500);
$('#title5').fadeOut(500);
setTimeout('fadeTitles();', 1100);
});
});
});
});

}

$(document).ready(function() {
fadeTitles();
});

daveVk

9:50 am on Mar 7, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this, be warned I am also JQuery newby

function fadeTitles() {
$('#title' + n ).fadeIn(500);
$('#title' + n ).fadeOut(500,fadeTitles };
n++;
if ( n > 5 ) { n=1; }
}

var n=1;

$(document).ready(function() {
fadeTitles();
});

Think last statement simplifies to
$(document).ready(fadeTitles);

dwpub

8:59 am on Mar 9, 2009 (gmt 0)

10+ Year Member



Thanks for your replies guys,

I actually found the answer on another forum post I added a call back to the function name on the last fadeout. i.e. $j('#title5').fadeOut(5000, funcname); This basically restarted the function after the last fadeout. Exactly what I wanted.

However, I didn't like the fact that I had little to no control over the display time and transition speed. After a bit of research I came across the cycle plugin, this does exactly what I want plus allows for a lot more control. You can check out the cycle plugin here: [malsup.com...]