-1

How can I add Class to some element not at once? I am looking for a way to add the class to the element with some delay(one by one) instead of applying the class to all at once.

$("button").click(function(){
    $("p").each(function(){
        $(this).addClass('blue');
    });
});
.blue {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add</button>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
halfer
  • 19,824
  • 17
  • 99
  • 186
Mona Coder
  • 6,212
  • 18
  • 66
  • 128
  • So, you’d use [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) or [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval). Which of those have you tried? – Sebastian Simon May 25 '18 at 22:28
  • Possible duplicate of [How to add pause between each iteration of jQuery .each()?](https://stackoverflow.com/questions/5202403/how-to-add-pause-between-each-iteration-of-jquery-each) – Sebastian Simon May 25 '18 at 22:29
  • you can try using closure and setInterval with delay. – Perry2008084 May 25 '18 at 22:30

2 Answers2

2

As mentioned in the comments, you can use setTimeout:

$("button").click(function(){
    $("p").each(function(index){
      const element = this;
      // Delay in ms
      const delay = index * 1000;

      setTimeout(function() {
        $(element).addClass('blue');
      }, delay);

    });
});
user3210641
  • 1,565
  • 1
  • 10
  • 14
-1

Try this snippet. It does nothing but break loop after each element.

$("button").click(function(e){
    $("p").not('.blue').each(function(){
        $(this).addClass('blue');
        return false;
    });
});
.blue {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add</button>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
<p>App </p>
ASammour
  • 865
  • 9
  • 12