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.

Sumit Bijvani
  • 8,154
  • 17
  • 50
  • 82

4 Answers4

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.net/kg4huLrL/2/

Dennis Jamin
  • 398
  • 1
  • 10
1

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

Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • This will add a .active class to áll siblings, might not be expected behaviour. Also: try and chain your calls; http://stackoverflow.com/a/25545165/1088868 – Dennis Jamin Aug 28 '14 at 09:22
  • @DennisJamin, This " want to remove active class from 1st li and add it to 2nd li and viceversa" says only two `li` present and OP want to toggle class between these two `li` – Bhushan Kawadkar Aug 28 '14 at 09:24
  • Fair ehough, your sollution however is not future- and waterproof. Mine however is more strict and covers all bases. – Dennis Jamin Aug 28 '14 at 09:31
1

You might want to use setInterval, see this posting on how to use it:

Stop setInterval

Community
  • 1
  • 1
Tom M.
  • 136
  • 3
0
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);
patrykf
  • 449
  • 5
  • 19
  • Why use a .each? Quite cluttery code, as this might be solved by just selecting the right item using a .active selector.. – Dennis Jamin Aug 28 '14 at 09:22