Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide elements until the page finishes loading - using jquery

I've just write a dead-simple code to hide all the elements until the page finishes loading and display an indicator while loading.. (It works).

so what I'm asking for is to know if I'm doing it right and what are you going to suggest.

HTML

<body>
    <div class="loading">
        <img src="indicator.gif"/>
    </div>

    <div class="content">
        <!-- page content goes here --> 
    </div>
</body>

jquery

$(document).ready(function(){
        $(".content").hide();
     });

    $(window).load(function(){
        $(".loading").fadeOut("slow");
        $(".content").fadeIn("slow");
     });
like image 342
Sam Avatar asked Sep 13 '11 09:09

Sam


People also ask

How do I hide elements on page load?

This is probably the most obvious way to hide the element ready for it to be displayed later on, either placing it in a <script> tag somewhere on the page or in one of your Javascript files: $(document). ready(function() { $('#example'). hide(); });

How do we hide the content in jQuery?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.

Which jQuery method is used to hide the elements?

The hide() is an inbuilt method in jQuery used to hide the selected element. Syntax: $(selector).

Can be used in jQuery to hide and display an element of HTML?

jQuery toggle() You can also toggle between hiding and showing an element with the toggle() method.


2 Answers

You probably want to hide the content div from the start to avoid any possible page flicker depending on what's being loaded on the page.

<body>
  <div class="loading">
    <img src="indicator.gif"/>
  </div>

  <div class="content" style="display: none;">
    <!-- page content goes here --> 
  </div>
</body>


$(window).load(function(){
  $(".loading").fadeOut("slow");
  $(".content").fadeIn("slow");
});
like image 136
njr101 Avatar answered Sep 19 '22 14:09

njr101


A slight improvement on this Javascript is to use a callback on the fadeout so the fade in starts when the fadeout has completed. This gives you a much smoother transition.

<body>
  <div class="loading">
    <img src="indicator.gif"/>
  </div>

  <div class="content" style="display: none;">
    <!-- page content goes here --> 
  </div>
</body>


$(window).load(function(){
  $(".loading").fadeOut("slow", function(){
    $(".content").fadeIn("slow");
  });
});
like image 43
nidal Avatar answered Sep 19 '22 14:09

nidal