A Better Way to {hide} with jQuery

Posted on January 22, 2009, by Matt, under CSS, Web, accessibility, jQuery.

Karl Swedberg has posted (some time ago) a great way to avoid the dreaded flash of “hidden” content when loading lengthy pages.

The typical approach is

<script type="text/javascript">
    $(document).ready(function(){   
        $("#id").hide();
    })
</script>

This will work fine on smaller pages, since the time between the document loading and being ready is relatively short. For more sizable pages, Karl proposes the following:

<script type="text/javascript">
      $('html').addClass('js');
      $(document).ready(function() {
        // Stuff to do as soon as the DOM is ready
      });
</script>

This simply adds the class of “js” to the entire HTML document. The magic is the addition of the following line to your stylesheet

.js #id {display: none;}

This now sets the “id” element, that now has a class of “js”, to display:none.

This solution supports progressive enhancement in that those who have CSS but no JavaScript will get all of the styled content.  Those without both, still get all of the content.

Leave a Comment