Mostafa Elkady
Mostafa Elkady

Reputation: 5801

add class in li after time and re-add from the first

i have ul like this

<ul>
    <li>one</li>
    <li>one</li>
    <li>one</li>        
</ul>

i want jquery code

  1. 1- add one the first li the current class
  2. after 2 second add on the second li
  3. and etc
  4. if its the last li re-make from the first

and i will never use a jquery plugin like cycle because i must do by my hand

Upvotes: 1

Views: 762

Answers (2)

jAndy
jAndy

Reputation: 236122

CSS:

li {
    display: none;
}

Javascript:

$(function() {
    var $list = $('ul li');

    $list.filter(':first').addClass('current');

    setInterval(function() {
        if( $list.filter('.current').index() !== $list.length - 1 ) {
            $list.filter('.current').removeClass('current').next().addClass('current');
        }
        else {
            $list.removeClass('current').filter(':first').addClass('current');
        }
    }, 2000);
});

Demo: http://www.jsfiddle.net/uQKX6/

Inspired by RightSaidFred:

$(function() {
    var $list = $('ul li'),
        tID   = null,
        i     = 0;

    function loop() {
        alert($list.removeClass('current').slice(i, i+1).addClass('current')[0].id);

        if( i < $list.length-1 ) i++;
        else i = 0;

        tID = setTimeout(loop, 2000);
    }

    $list.hover(function() {
        clearTimeout(tID);
    }, function() {
        loop();
    });

    loop();
});

Demo: http://www.jsfiddle.net/uQKX6/4/

Upvotes: 3

RightSaidFred
RightSaidFred

Reputation: 11327

var lis = $('ul > li');

function switchClass(i) {
    lis.eq(i).removeClass('current');
    lis.eq(i = ++i % lis.length).addClass('current');
    setTimeout(function() { switchClass(i); }, 2000);
}
switchClass(-1);

http://jsfiddle.net/7ec63/

Upvotes: 1

Related Questions