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);;
}
1
  • you need to delay the loop, not the display code Commented Aug 2, 2016 at 0:09

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.