user7548524
user7548524

Reputation: 53

looping in jquery (with .each() method)

I have made the following code in order to create something like a piano. When you click on a button (#start_img) each .piano div should get the press class and after a short break it should be removed from it again.

Then the function should loop to the next .piano div and repeat the same actions there. Doesn't sound too difficult, only problem is that it isn't working. Can anyone explain to me what's wrong with the code?

$('#start_img').on('click', function() {
  $('.piano').each(function(index) {
    $(this).addClass('press').delay(900).removeClass('press');
  });
});
.press {
  background-color: silver;
}
.piano {
  border: 1px solid black;
  display: inline-block;
  width: 20px;
  height: 60px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id='start_img'>Start</button>

<div id='page'>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
  <div class='piano'></div>
</div>

Upvotes: 1

Views: 33

Answers (2)

Jai
Jai

Reputation: 74738

You can use setTimeout with a delay at the particular index.

start.on('click', function() {
  var piano = $('.piano');
  piano.each(function(index) {
    var _this = $(this);
    _this.addClass('press');
    setTimeout(function() {
      _this.removeClass('press');
    }, 900 * index);
  });
});

Upvotes: 0

charlietfl
charlietfl

Reputation: 171698

Two reasons.

  1. delay() will only work for methods that use the animation queue internally
  2. The loop will run instantaneously and therefore add same delay to each instance making them all activate simultaneously

You could do something like

piano.each(function(index){
   var $el = $(this);
   setTimeout(function(){
       $el.addClass('press');
       setTimeout(function(){
         $el.removeClass('press');
       }, 880);
   }, (index+1) * 900);// multiply delay by index to increment each one
});

Upvotes: 1

Related Questions