Search code examples
htmljquerypreloader

Delay a preloader fadeout with jquery


I see there are lots of questions on here about this but I can't seem to implement it properly into my site. I'm trying to get my preloader to run for the length of the gif (3 seconds) before fading out. My code is

jQuery(document).ready(function($) {
    $(window).load(function(){
        jQuery('#preloader').fadeOut('slow',function(){jQuery(this).remove();});
    });
});

I see that I should probably use a setTimeout, but I can't seem to figure it out. Any tips?

I realize my code here performs the fadeout when the page loads rather than after time, but having trouble implementing the latter.


Solution

  • As the fadeOut() uses the jQuery fx queue you can use delay() to achieve this:

    jQuery($ => {
      $(window).on('load', () => {
        $('#preloader').delay(3000).fadeOut('slow', function() {
          $(this).remove();
        });
      });
    });
    

    Alternatively you can use setTimeout() as you mentioned in the question:

    jQuery($ => {
      $(window).on('load', () => {
        setTimeout(() => {
          $('#preloader').fadeOut('slow', function() {
            $(this).remove();
          });
        }, 3000);
      });
    });