Ancinek Ancinek - 29 days ago 9
Javascript Question

jQuery - delay after addClass in each loop

I want to add class

editing
to my links but with a nice animation, so I need the each class to be added after slight delay.

How can I achieve this?
I tried with inserting and empty
setTimeout
inside the loop but it didn't work.

var $links = $('.my_box .link');
$link.each(function() {
$(this).addClass('editing');
// A delay should be here
});

Answer

You can do this with delay and queue:

function markLinks() {
  var $links = $('.my_box .link');
  $links.each(function(i) {
    var $this = $(this);
    $this.delay(i * 200).queue(function() {
      $this.toggleClass("editing").dequeue();
    });
  });
  setTimeout(markLinks, 1500);
}
markLinks();
.editing {
  background-color: yellow;
}
<div class="my_box">
  <div class="link">one</div>
  <div class="link">two</div>
  <div class="link">three</div>
  <div class="link">four</div>
  <div class="link">five</div>
  <div class="link">six</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

delay sets a delay in the animation queue, and queue schedules a function call on that queue. Note that you need to dequeue in the queue callback, since the nature of animation is that that callback might be starting something that it finishes later (but in your case, you aren't).

Comments