Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});
like image 395
mdmb Avatar asked Jun 28 '26 05:06

mdmb


1 Answers

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).

like image 199
T.J. Crowder Avatar answered Jun 29 '26 21:06

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!