will0956
will0956

Reputation: 41

Preloader JavaScript

I'm trying to make a preloader, I currently have this code, but it's not showing the preloader before the page loads.

$(document).ready(function(){
        $(".preloader-wrapper").show();
        $("body").hide();
     });

$(window).load(function(){
  $(".preloader-wrapper").fadeOut("slow", function(){
    $("body").fadeIn("slow");
  });
});

EDIT: Got it.

setTimeout(function() {
  $('#preloader').fadeOut('slow', function() {
    $(this).remove();
  });
}, 2000);

#preloader {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  width: 100%;
  height: 100%;
  overflow: visible;
  background: #333 url('http://files.mimoymima.com/images/loading.gif') no-repeat center center;
}

Upvotes: 0

Views: 1944

Answers (4)

Subash Chandra
Subash Chandra

Reputation: 26

Try this simple Preloader with css and javascript. no need to add any library. Sample Blog : https://www.kingsubash.com/simple-page-preloader-with-css-and-javascript

window.onload = function(){
//hide the preloader
document.querySelector(".preloader").style.display = "none";

}

.preloader{position: fixed;top: 0;left: 0;width: 100%;height: 100vh;background: #fff;z-index: 9999;text-align: center;}.preloader-icon{position: relative;top: 45%;width: 100px;border-radius: 50%;}


<div class="preloader"> <img class="preloader-icon" src="/PATH-TO-IMAGE" alt="My Site Preloader"> </div>

Upvotes: 0

Roger
Roger

Reputation: 3256

You can have it loaded first and on top. Then just remove it after the dom is loaded.

setTimeout(function() {
  $('#preloader').fadeOut('slow', function() {
    $(this).remove();
  });
}, 2000);
#preloader {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  width: 100%;
  height: 100%;
  overflow: visible;
  background: #333 url('http://files.mimoymima.com/images/loading.gif') no-repeat center center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="preloader"></div>
<h1>SUPER SIMPLE FULL PAGE PRELOADER</h1>

Upvotes: 2

Jamie R Rytlewski
Jamie R Rytlewski

Reputation: 1221

One of the issues is that you are hiding the entire body, which probably includes the .preloader-wrapper

Upvotes: 1

Jakub Rożek
Jakub Rożek

Reputation: 2130

You should set the .preloader-wrapper to be visible as default - use css for this.

Example:

.preloader-wrapper { 
  display: block;
}

Also, you shouldn't place something outside the <body> tag, so this means you shouldn't hide body using JS.

Remove:

$(document).ready(function(){
    $(".preloader-wrapper").show();
    $("body").hide();
 });

Change the second piece of your code to:

$(window).load(function(){ 
  $(".preloader-wrapper").fadeOut("slow");
});

Upvotes: 1

Related Questions