4

I'm using jQuery Accordion. When the page loads, all the divs flash for a second before being hidden. I'd like the divs to stay hidden while loading. I thought I was doing that by setting them to hidden via javascript outside of the document ready check like so:

$('#accordion div').hide();
$('#accordion2 div').hide();

jQuery(document).ready(function($) {...

However this isn't working and I suspect it's because I'm using the $ shortcut not yet declared.

How do I get the hide() functions to fire while the page is loading instead of waiting until it is fully loaded and then hiding the divs?

Thanks!

Yazmin
  • 1,154
  • 5
  • 17
  • 34
  • Please give more details like your html. You are probably trying to hide something that doesn't exist yet. – c0mm0n May 07 '11 at 20:38

2 Answers2

7

The reason that it's not working is because you are trying to hide the elements before they exist. It would work if you put the code at the end of the page, but even then you are not sure that they are not visible for a split second.

Use CSS to hide them instead, then they are hidden already when they come into existance:

<style type="text/css">

#accordion div, #accordion2 div { display: none; }

</style>
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I thought I had tried this before and it didn't work, but just tried it now and it worked. I must have had something else stopping the code from working appropriately. Thanks. – Yazmin May 10 '11 at 00:43
  • 1
    @Kwestion: Yes, this method is the best way to hide elements initially. If you have a style sheet for the page you would rather put the rule there than in a style tag. – Guffa May 29 '14 at 22:23
3

These statements try to hide something that has not been loaded yet:

$('#accordion div').hide();
$('#accordion2 div').hide();

With jQuery you should write this:

$(function(){
    $('#accordion div').hide();
    $('#accordion2 div').hide();
});

So, the code will be executed after the skeleton of html document will be loaded

bitfox
  • 2,281
  • 1
  • 18
  • 17
  • This solution works as well, but will flash all the divs on a page refresh. Thank you correcting my code. – Yazmin May 10 '11 at 00:44