Can't hide div before alert

Viewed 295

I got a request for removing a div and showing an alert. Therefore, my first code is as follows:

$(document).ready(function(){

 $('#headerDiv').hide();

 alert('something wants to say');

});

It didn't the hide div before the alert in chrome and edge, so I change the alert line to

setTimeout(function(){

 alert('something wants to say');

},100);

It works fine but I want to know why it happens. Furthermore, I think the problem can occur again depending on computer performance, so I want to know if there is any quality fix or not.

3 Answers

setTimeout is pushed at the end of the current stack execution, hence gives the browser the time to interrupt the JS and render the changes. setTimeout is a possible solution to this.

One other possibility could be to fire an event after the .hide() that triggers the alert.

(you can find more about the setTimeout implementation here

This is because JS is executed first before any change. There are many things you can do.

  1. Use a different way to show alert, like an overlay.
  2. Use a Promise
  3. Trigger an event after the hide, and bind the alert to that event.

You can try the below solution, It will show the alert when the hide will complete. It will not depend on your system's performance.

$(document).ready(function(){
  $('#headerDiv').hide({done: function() { alert("something want to say!"); } });
  //** you can still add a delay */
  //$('#headerDiv').hide({done: function() { setTimeout(function(){alert("Hiding complete!") },100) }});
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="headerDiv"> headerDiv headerDiv</div>

Related