how to add timer to jquery loading div?

Viewed 543

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>
3 Answers

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

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>

Related