JavaScript: Continuously loop through children using jQuery
<html>
<head>
<style>
#items{ margin:0; padding:0; }
/* hide all items initially */
#items li{ display:none; list-style:none; position:absolute; }
/* show the item that has the 'show' class */
#items li.show{ display:block; }
</style>
</head>
<body>
<ul id="items">
<li class="show">Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<!-- include jQuery core code -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
function textloop() {
// get the item that currently has the 'show' class
var current = $("#items .show");
/*
* find the next item with some help from jQuery's ternary operator
* the syntax for the ternary operator is 'a ? b : c'
* in other words 'if a is true return b otherwise return c'
*/
var next = current.next().length ? current.next() : current.parent().children(':first');
// fade out the current item and remove the 'show' class
current.fadeOut(3000,function(){
// fade in the next item and add the 'show' class
next.fadeIn("slow").addClass("show");
}).removeClass("show");
// repeat by calling the textloop method again after 3 seconds
setTimeout(textloop,3000);
}
// call the text loop method when the page loads
textloop();
});
</script>
</body>
</html>