Aiden P Aiden P - 2 months ago 12
CSS Question

How to hide elements one by one then show them one by one using jquery?

Trying to hide one div at a time (5 seconds intervals between each) and when the third one gets hidden the first one shows right away. And like that infinitely.

I tried this but it's not working well. Hides them successfully but doesn't show them.



setTimeout(function() {
$('#span3').hide();
}, 5000);

setTimeout(function() {
$('#span2').hide();
}, 10000);

setTimeout(function() {
$('#span1').hide();
}, 15000);

setTimeout(function() {
$('#span3').show();
}, 15000);

setTimeout(function() {
$('#span2').show();
}, 20000);

setTimeout(function() {
$('#span1').show();
}, 25000);

.appear-span div span {
display: block;
background-color: black;
padding: 5px 0;
color: white;
width: 200px;
text-align: center;
position: absolute;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="appear-span">
<div id="span3">
<span>Selling food.</span>
</div>
<div id="span2">
<span>Selling drink.</span>
</div>
<div id="span1">
<span>Selling kidneys.</span>
</div>
</div>





Where do I add the timings if I want them to hide 5 seconds one after the other?

$("#span3").hide(function(){
$("#span2").hide(function(){
$("#span1").hide(function(){
});
});
});

Answer

Just nest the calls and then recall the same function, use jquery delay.

$(function() {
var delayInterval = 5000;
function hideAndPeek() {
    $('#span3').delay(delayInterval).hide(function() {
        $('#span2').delay(delayInterval).hide(function() {
            $('#span1').delay(delayInterval).hide(function() {
                $('#span3').delay(delayInterval).show(function() {
                    $('#span2').delay(delayInterval).show(function() {
                        $('#span1').delay(delayInterval).show(function() {
                            hideAndPeek();
                        });
                    });
                });
            });
        });
    });
}
setTimeout(hideAndPeek(), delayInterval);
});

  
  p {
    font-size: 150%;
    cursor: pointer;
  }
<body>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <div class="appear-span">
    <div id="span3">
      <span>Selling food.</span>
   </div>
  <div id="span2">
    <span>Selling drink.</span>
  </div>
  <div id="span1">
    <span>Selling kidneys.</span>
  </div>
 </div>
</body>