0

i have an array of 3 items. i want to display each item with a delay in between and remove the previous one. my code works for displaying each item but i can't remove the previous one. if i add html('') at the end of each loop.. it'll remove everything before the item gets display due to the delay. here is jsfiddle https://jsfiddle.net/qawzzzjz/

<div class='view'>
</div>

var arr = ['First', 'Second', 'Third'];

for(var i=1; i<arr.length+1; i++){
$("<h3 style='display: none;'>"+arr[i-1]+"</h3>").appendTo('.view').delay(1000*i).fadeIn(500);

}

I also tried this code but it only shows the third item

var arr = ['First', 'Second', 'Third'];

for(var i=1; i<arr.length+1; i++){
$('.view').html("<h3>"+arr[i-1]+"</h3>").delay(1000*i);;
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
lys916
  • 307
  • 2
  • 5
  • 18

2 Answers2

2

Just add FadeOut on end of your line and it will work. See example:

var arr = ['First', 'Second', 'Third'];

for(var i=1; i<arr.length+1; i++){
 $("<h3 style='display: none;'>"+arr[i-1]+"</h3>").appendTo('.view').delay(1000*i).fadeIn(500).fadeOut(500);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = 'view'>
  
</div>
Aleksandar Đokić
  • 2,118
  • 17
  • 35
1

if you use setTimeout (which .delay uses behind the scene) you can remove the prev one before adding the new one. You can even put a fadeout effect on it if you want instead of a remove, just anything you want :p

var arr = ['First', 'Second', 'Third'];

for(var i=0; i<arr.length; i++){
  setTimeout(function(val) {
  if(val!==0){
     $('.view').children()[0].remove();
    }
    $("<h3 style='display: none;'>"+arr[val] +"</h3>").appendTo('.view').fadeIn(500);
  }, 1000*i, i);
 

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='view'>

</div>

a post that might help you understand the code: other question

Community
  • 1
  • 1
miThom
  • 373
  • 2
  • 11