Reputation: 1989
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
Reputation: 57105
function addcls() {
var $this = $('#slider ul li.current').removeClass('current');
$this.next('li').addClass('current');
};
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
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
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