最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery add class to current li and remove prev li automatic - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 5

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/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);
发布评论

评论列表(0)

  1. 暂无评论