Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and remove class from list using jquery

I have an unordered HTML list such as this:

<ul>
    <li class="current"></li>
    <li></li>
    <li></li>
</ul>

Using jquery, I would like to automatically remove the current class from the first li element and add it to the second class. After a short period of time I would like to remove the class from the second li element and add it to the third. I would like for this to repeat as well.

I have this so far but it's not at all what I need:

 $("ul li:first-child").addClass('current').delay(1000).queue(function(next){
    $(this).removeClass('current');
    $(this).next().addClass('current')
    next();
});
like image 824
user2137425 Avatar asked Sep 16 '25 22:09

user2137425


1 Answers

If you want to be able to stop and start it:

var myInterval;
var myFunc = function() {
        var cur = $('ul li.current');
        if(cur.index() == $('ul li').length - 1) {
            cur.removeClass('current');
            $('ul li:first').addClass('current');
        } else {
            cur.removeClass('current').next().addClass('current');
        }
    };
//Start Interval
myInterval = setInterval(myFunc, 1000);

Then, to stop/start:

clearInterval(myInterval);
myInterval = setInterval(myFunc, 1000);

jsFiddle

like image 147
Marcus Avatar answered Sep 19 '25 13:09

Marcus