0

I have a series of spans that I want to fade in sequentially. I'm trying to use a for loop to loop through the spans to show them all by adding a class of show (which changes visibility) and using a setTimeout inside the loop to slightly delay the class being added on each span. It seems to only add the 'show' class to the very last span of the div but it tries adding it to the one span 6 times (it console logs the same span class six times).

(I'm using javascript instead of jquery to add class because I get an error that currentSeat.addClass is not a function--another thing I can't figure out)

What am I doing wrong??

Thanks in advance!

var seat = $('.seat-fillup span');
for (var i = 0; i < seat.length; i++) {
  var currentSeat = seat[i];
  setTimeout(function(){
    currentSeat.classList.add('show');
  }, 50 * i);
}
.seat-fillup span {
  visibility: hidden;
}
.seat-fillup span.show {
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seat-fillup">
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
</div>
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
njpatten
  • 165
  • 1
  • 3
  • 15

2 Answers2

1

You need to use closure and use .eq() to get the element

jQuery(function($) {
  var seat = $('.seat-fillup span');
  for (var i = 0; i < seat.length; i++) {
    (function(index) {
      setTimeout(function() {
        seat.eq(index).addClass('show');
      }, 500 * index);
    })(i)
  }
})
.seat-fillup span {
  visibility: hidden;
}
.seat-fillup span.show {
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seat-fillup">
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
  <span>Image here</span>
</div>
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

you wanna do (function(e){setTimeout(function(){ e.classList.add('show'); }, 50 * i);})(currentSeat);

Adam
  • 1,342
  • 7
  • 15