Pelle2010
Pelle2010

Reputation: 143

jQuery Preloader with min-time

Heyo,

I was wondering if there would be a way to set a min-time to an onload function so that the div is shown min 2sec. Basicly the same as with min-width or min-height. If the site is taking longer than 2sec to load, the div will still be shown untill the site is fully loaded but when the site takes less than 2sec to load the div will still be displayed for a minimum of 2sec.

Here is my current code:

$(window).on('load', function() {
    $('.preloader').delay(350).fadeOut('slow');
});

Upvotes: 1

Views: 1217

Answers (2)

Guilherme Rossato
Guilherme Rossato

Reputation: 711

So I take it you want a function to be run when either: the page loads or after 2 seconds, whatever comes later.

First, define a function to be called:

function load_func() {
    $('.preloader').delay(350).fadeOut('slow');
}

Then, let's define a way to call the function in either situation:

var pageLoaded = false;
var timeoutElapsed = false;

$(window).on('load', function() {
    pageLoaded = true;
    if (timeoutElapsed) {
        load_func();
    }
});

setTimeout(function() {
    timeoutElapsed = true;
    if (pageLoaded) {
        load_func();
    }
}, 2000);

This way, if the page loads before 2 seconds, it will wait the timeout to call the function.

Otherwise, if the page loads after 2 seconds, it will call it whenever that load event happened.

Upvotes: 0

javimovi
javimovi

Reputation: 386

Try this:

 $(window).on('load', function() {
        setTimeout( function(){
           $('.preloader').fadeOut('slow'); 
        }, 2000 )
    });

Upvotes: 2

Related Questions