Jack Gleeman Jack Gleeman - 4 months ago 13
Javascript Question

Gif not fading out despite calling .fadeOut command

I am trying to get a gif that I have to fade out after the page loads, but I'm not having much luck.

I want the overlay, which has a white background and the gif, to fade into transparency after everything else on the page is loaded and ready to be seen.

Below is my code, and also a link to a page where I've been testing it:

Link to test code

any ideas?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.1.0.slim.min.js"
integrity="sha256-cRpWjoSOw5KcyIOaZNo4i6fZ9tKPhYYb6i5T9RSVJG8="
crossorigin="anonymous"></script>
<div id="overlay">
<img src="https://www.isostech.com/wp-content/uploads/2015/04/loader.gif" alt="Loading" /><br/>
Loading...
</div>
Hello World!

<script>
$(window).load(function(){
$('#overlay').fadeOut();
});
</script>


And the CSS:

#overlay {
background-color: white;
color: #666666;
position: fixed;
height: 100%;
width: 100%;
z-index: 5000;
top: 0;
left: 0;
float: left;
text-align: center;
padding-top: 25%;
}

Answer

You use multiple versions of jQuery. If you either delete the include for jQuery 3, or make the following change, it will work.

I recently contributed to document-ready handlers in the SO:Docs which applies here and I think many will not realize as they switch to jQuery 3.

jQuery(function($) {
  // Run when document is ready
  // $ (first argument) will be internal reference to jQuery
  // Never rely on $ being a reference to jQuery in the global namespace
});

All other document-ready handlers are deprecated in jQuery 3.0.

Using that doc-ready handler will work even if you leave both jQuery includes in the code.