Reputation: 127
say you have this html
<ul class="nav sub_nav_home">
<li id="sub_nav_home1"><a href="#"><span>LINK1</span></a></li>
<li id="sub_nav_home2"><a href="#"><span>LINK2</span></a></li>
<li id="sub_nav_home3"><a href="#"><span>LINK3</span></a></li>
</ul>
how do you iterate through each "li" in jquery adding a class "current", waiting for 3 seconds and then moving onto the next "li, and once you get to the end start again?
Thanks
Upvotes: 2
Views: 3027
Reputation: 630369
A simple solution might look like this:
$(function() {
var nav = $("ul.sub_nav_home");
setInterval(function() {
var next = nav.find("li.current + li, li:first-child").last();
nav.find("li.current").removeClass("current");
next.addClass("current");
}, 3000);
});
You can give it a try here. You can compact this down a bit more, just trying to clearly lay out what's going on. What this does is run the executed function every 3 seconds, we find the <ul>
from the start to cache things, then on each run we get the one after the .current
<li>
(if there is one) and the first, in case we're at the end. We take the last of those (since they're in document order), so we always prefer the next one over looping back to the start. Then just remove the class from the current one and add it to the next in line.
Upvotes: 3
Reputation: 2788
I think you need this...
jQuery('#nav sub_nav_home li').each()
Upvotes: 0