2

I've tried using the below code to have a div display as a loading screen. But it dissapears as soon as the page loads.. I want it to stay for 5 seconds while things in the background load, and then dissapear. How do I do this? I tried adding setTimeout but it didn't do anything

$(window).on('load', function () {
    setTimeout(document.getElementById("loading").style.display = "none", 5000)
});
#loading {
    display: block;
    opacity: 1;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
    width: 100vw;
    height: 100vh;
    background-color: $black;
}

.loading_logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
<div id="loading">
    <img class="loading_logo" src="<?php echo get_template_directory_uri();?>/lib/images/header-logo.svg">
</div>
1
  • Start by reading the setTimeout() documentation
    – charlietfl
    Commented Nov 1, 2020 at 23:08

3 Answers 3

2

setTimeout should be

setTimeout(() => document.getElementById("loading").style.display = "none", 5000); // ES6 syntax

Or

setTimeout(function() { 
  document.getElementById("loading").style.display = "none"
}, 5000); // ES5 syntax
2

You need to use setTimeout with a callback function like so

setTimeout(function(){
    document.getElementById("loading").style.display = "none";
}, 5000)

The function will run after 5000 miliseconds.

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

1

Here's a jsfiddle: https://jsfiddle.net/tg1r4dpq/

Also, you can run the code below.

function loadingImg() {
    var loading_logo = document.getElementById("loading_logo");
    setTimeout(function() {
    loading_logo.style.visibility = "hidden"
  }, 5000);
}

loadingImg();
#loading {
    display: block;
    opacity: 1;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
    width: 100vw;
    height: 100vh;
    background-color: $black;
}

.loading_logo {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
<div id="loading">
    <img src="https://placehold.it/100x100" alt="" id="loading_logo" class="loading_logo" />
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.