web
analytics

Hiding unstyled div that shows on page load

Posted by on Mar 26, 2010 in Javascript, Tech | One Comment

In the spirit of sharing web development tips and techniques:

Have you come across a situation where you have a javascript carousel or accordian that is fairly content heavy? When the page loads the list items or the div content flash onto the screen until the page loads and then the whole page “pops” into place.  Very annoying effect when you’re on a slower connection.

I dealt with this problem on the home page of the new auditel.co.uk site.  On this page I’m using the excellent jQuery library and a modified version of the useful plugin called jflow that allows for autoscrolling.  The technique below was documented on the Learning jQuery site and uses a combination of javascript and css to hide the extra content until the page finishes loading.

<html>
<head>
<!– etc. –>

// The style below can be placed in your external css file
<style type=”text/css”>
.js .flash {display: none;}
</style>

// Usual javascript loaded below, note the .addclass() method used BEFORE the $(document).ready()
<script type=”text/javascript” src=”/scripts/jquery.js”></script>
<script type=”text/javascript”>
$(‘html’).addClass(‘js’);
$(document).ready(function() {
// Stuff to do as soon as the DOM is ready, in my case this has my settings for the jflow plugin
});
</script>

// The javascript below will make your div content below once the page is loaded
<script type=”text/javascript”>
$(window).bind(‘load’, function() {
$(‘div.showthis’).show();
});
</script>

</head>
<body>

// Included in the body of the html are the set of divs that make up the carousel or accordian
<div>
Show the content in the first div.
</div>
<div class=”flash showthis”>
Hide the content in the second div.
</div>

<!– etc. –>

</body>
</html>

Hope the code above helps someone, can be one of those problems that cause hours of frustrated searching around.  Please let me know if you see any problems or can recommend a better method.

1 Comment

  1. Steve Haigh
    April 13, 2010

    Genius! You;ve saved me a whole load of pain on my website. I use a slide down box to allow people to navigate to other examples of my work and all the images we’re visible on page loads.

    I’ve used your magic to fix it.

    Thanks,
    Steve