2

jQuery how to add a class to an element one by one with a small delay when click on the #button ? not to add the class at once for all element.I want to do it one by one. Please help. Thanks in advance.

<ul id="scroll-set">
<li class="  imVisible">Brentwood</li>
<li class="imVisible ">Antioch</li>
<li class=" imVisible">Pittsburg</li>
<li class=" imVisible">Concord</li>
<li class="imVisible ">Walnut Creek</li>
<li class=" imVisible">Danville</li>
<li class=" imVisible">San Ramon</li>

</ul>
<div id="button">
Kasun Malith
  • 83
  • 1
  • 7
  • This may help you http://stackoverflow.com/questions/7302824/animating-addclass-removeclass-with-jquery – techie_28 Sep 21 '12 at 07:17

3 Answers3

15

The working demo.

$('#button').click(function() {
  $('#scroll-set li').each(function(i) {
    var $li = $(this);
    setTimeout(function() {
      $li.addClass('imVisible');
    }, i*100); // delay 100 ms
  });
});


The reverse version.
$('#button').click(function() {
  $($('#scroll-set li').get().reverse()).each(function(i) {
    var $li = $(this);
    setTimeout(function() {
      $li.addClass('imVisible');
    }, i*100); // delay 100 ms
  });
});

xdazz
  • 158,678
  • 38
  • 247
  • 274
3

You can use setInterval:

$(function(){
  var el = $('li');
  var index = 0;
  var timer = window.setInterval(function(){
    if  (index < el.length) {
      el-eq(index++).addClass('imVisible');
    } else {
      window.clearInterval(timer);
    }
  }, 500);
});

Demo: http://jsfiddle.net/bdUxa/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

do a settimeout with a delay and set the classname by the index and it should work.

var i=0;
function changeClass()
{
    if(i<document.getElementById("scroll-set").childNodes.length)
    {
        document.getElementById("scroll-set").childNodes[i].className= "whateverclassname";
        i++;
        setTimeout(changeClass,1000);
    }
}

let me know if it works.