Hide div onload function JS

Viewed 66

I just want to hide this div onload but it's not working.

Here is the snippet:

$(window).load(function() {
    $('.preloader').fadeOut('slow');
});
.preloader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background-image: url('loading.gif');
    background-repeat: no-repeat;
    background-color: #8f8f8f;
    background-position: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="preloader"></div>

2 Answers

I have added the working snippet, temporary I have added a timeout to see the effect of fadeOut. You can use jQuery with $(document).ready function to make it work.

$(document).ready(function() {
  setTimeout(function() {
    $('.preloader').fadeOut('slow');
  }, 3000);
});
.preloader {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-image: url('loading.gif');
  background-repeat: no-repeat;
  background-color: #8f8f8f;
  background-position: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="preloader"></div>

The load() method as you use it only works with jQuery versions less than 3.0.0

Note: Prior to jQuery 3.0, the event handling suite also had a method named .load(). Older versions of jQuery determined which method to fire based on the set of arguments passed to it.

Working snippet with jQuery version 2.2.4:

$(window).load(function() {
    $('.preloader').fadeOut('slow');
});
.preloader {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 9999;
    background-image: url('loading.gif');
    background-repeat: no-repeat;
    background-color: #8f8f8f;
    background-position: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="preloader"></div>

But I suggest to use the latest version of jQuery and the ready() method as proposed by ankitkanojia:

$(document).ready(function() {
    $('.preloader').fadeOut('slow');
});
Related