Reputation: 8179
Below is my HTML code, I want to remove active
class from 1st li
and add it to 2nd li
and viceversa automatic every 2 second using jQuery.
<li class="">
<a href="#">
<img src="client_logo01.png">
</a>
</li>
<li class="active">
<a href="#">
<img src="client_logo02.png">
</a>
</li>
I'm trying to do in this way.
$('ul li a').click(function() {
$('ul li.current').removeClass('active');
$(this).closest('li').addClass('active');
});
But it is only working on click event.
Upvotes: 0
Views: 5261
Reputation: 386
Pretty obvious it only get's executed on click, as you only bound a click event..
setInterval(function()
{
// Remove .active class from the active li, select next li sibling.
var next = $('ul li.active').removeClass('active').next('li');
// Did we reach the last element? Of so: select first sibling
if (!next.length) next = next.prevObject.siblings(':first');
// Add .active class to the li next in line.
next.addClass('active');
}, 2000);
Run this on document ready and the script alters the active class onto the next sibling every 2 seconds.
this runs regardless of the number of li children your ul element has
jsfiddle demo: http://jsfiddle.net/kg4huLrL/2/
Upvotes: 5
Reputation: 449
setInterval(function() {
if($('ul').find('li.active').eq(0).next('li') != undefined) {
$('ul').find('li.active').eq(0).removeClass('active').next('li').addClass('active');
} else {
$('ul').find('li.active').eq(0).removeClass('active');
$('ul').find('li').eq(0).addClass('active');
}
}, 2000);
Upvotes: 0
Reputation: 136
You might want to use setInterval, see this posting on how to use it:
Upvotes: 1
Reputation: 28513
Try this : remove active
class from li
with active
class and put active
class to its sibling li
setInterval(function(){
var $active = $('ul li.active');
$active.removeClass('active');
$active.siblings().addClass('active');
},2000);
Upvotes: 1