0

I am trying to perform something pretty easy at first glance but I can not do it. I have a button, and two hidden div. When the button is pushed, I want the first div to show and after n seconds, to hide and then the second div show.

html :

<button id="button">
  push
</button>
<div id="div1" style="display:none">
  firstDiv
</div>
<div id="div2" style="display:none">
  secondDiv
</div>

The whole code, with the JS is here : https://jsfiddle.net/439xbfe5/

I have already checked the answers here : jQuery show for 5 seconds then hide

The problem for this code is #div2 shows up before #div1 disapears :

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show().delay(timeLimit).fadeOut();
  $("#div2").show();
  
});

Same problem here :

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show();
  setTimeout(function() { $("#div1").hide(); }, timeLimit );
  $("#div2").show();
  
});

I also tried to create a blocking sleep function like :

function sleep(ms){
  var start = new Date().getTime();
  while(true){ 
    if(new Date().getTime()-start>ms){
        return; 
     }
  }
}

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show();
  sleep(timeLimit);
  $("#div2").show();
});

But this doesnt work at all.

Also, showing #div2 is just an illustration of my problem. Actually, I dont need to 'compilate' show then hide but #div1 is more like a transition step between before and after the button is pushed. I hope you understood my problem (sorry for my english).

Thx !

Maxime D.
  • 306
  • 5
  • 17

1 Answers1

1

You have to use the complete callback function to do something "after" a jquery animation is done.

$("#button").click(()=>{

  var timeLimit = 5000;
  $("#div1").show().delay(timeLimit).fadeOut(function(){
    $("#div2").show();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">
  push
</button>
<div id="div1" style="display:none">
  firstDiv
</div>
<div id="div2" style="display:none">
  secondDiv
</div>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Thank you this works pretty well. The problem is that I can't use a callback function because the actual code is pretty different. To illustrate, instead of button click event, I have a function transition() doing this show then hide animation. This function is called several times, that is why I can not use complete callback function. – Maxime D. Dec 14 '20 at 16:11