Steve Bals
Steve Bals

Reputation: 1989

add dynamic class to ul li with set interval timing

function addcls() {
        $('#slider ul li.current').removeClass('current');
        $(this).closest('li').addClass('current');
    };

 setInterval(function () {
        addcls();
       }, 3000);

the above code removing 'current' class from first li tag but not inserting to the next li tag. how to achieve this with set interval

html

<ul>
        <li class="current">SLIDE 1</li>
    <li class="" style="background: #aaa;">SLIDE 2</li>
    <li class="">SLIDE 3</li>
    <li class="" style="background: #aaa;">SLIDE 4</li>
  </ul>  

Upvotes: 0

Views: 1102

Answers (3)

.next()

function addcls() {
        var $this = $('#slider ul li.current').removeClass('current');
        $this.next('li').addClass('current');
    };


If you want to loop through

function addcls() {
    var $this =$('#slider ul li.current').removeClass('current');
    if ($this.next('li').length > 0) { //if next element is there 
        $this.next('li').addClass('current'); //add class to next to next element 
    } else { 
        $this.closest('ul').find('li:eq(0)').addClass('current'); //else add class to 1 st element 
    }
};

Upvotes: 1

Alex
Alex

Reputation: 10226

$(this) makes no sense in your function, does it?

function addcls() {
        var current = $('#slider ul li.current').removeClass('current'),
            next = current.next().length ? current.next() : current.siblings().filter(':first');
        next.addClass('current');
    };

 setInterval(function () {
        addcls();
       }, 3000);

Upvotes: 3

Felix
Felix

Reputation: 38112

closest() traverse up the DOM tree and get the first matched ancestor.

Your list items is the siblings of each other so you can use siblings() instead:

$(this).siblings('li').addClass('current');

Upvotes: 0

Related Questions