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.
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.
Share Improve this question asked Aug 28, 2014 at 9:13 Sumit BijvaniSumit Bijvani 8,17718 gold badges52 silver badges83 bronze badges 2- you can use setInterval(setClass, 2000); – jsdev Commented Aug 28, 2014 at 9:18
- @Bokdem "vice versa" means "the other way around" – rollingBalls Commented Aug 28, 2014 at 9:21
4 Answers
Reset to default 5Pretty 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/kg4huLrL/2/
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);
Demo
You might want to use setInterval, see this posting on how to use it:
Stop setInterval
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);