mubarmg mubarmg - 5 months ago 10
jQuery Question

jQuery : How can showint text and hide then showing another?

I'm trying to showing three lines of text , each line must to show after the previews line hide.

this is my html code:

<p id="line1">First Line</p>
<p id="line2">Second Line</p>
<p id="line3">Third Line</p>


I want to showing the (line1) and wait for 5 seconds then I want to hide it , After that showing the next line and wait for 5 seconds and hide it ... etc.

the problem is when I using :

$('#line1').show().delay(5000).hide();
$('#line2').show().delay(5000).hide();
$('#line3').show().delay(5000).hide();


all of them , showing together and hide together. I want to make it in queue , first one , then second ..... etc.

I need your help

Answer

Do them inside success callback

function cycle() {
  $("#line1").show().delay(5000).hide(function() {
    $("#line2").show().delay(5000).hide(function() {
      $("#line3").show().delay(5000).hide(cycle);
    });
  });
}
cycle();

You can make it more simple using an id of array.

var arr = ["#line1", "#line2", "#line3"]
i = 0;

function cycle() {
  $(arr[i]).show().delay(5000).hide(cycle); 
  i = (i + 1) % arr.length;
}
cycle();

If there are many elements with the id start with line then do something like

var $ele = $('[id^="line1"]'),
i = 0; 

function cycle() {
  $ele[i].show().delay(5000).hide(cycle); 
  i = (i + 1) % arr.length;
}
cycle();