How to hide elements with jQuery before they get rendered? How to hide elements with jQuery before they get rendered? jquery jquery

How to hide elements with jQuery before they get rendered?


@Andrew,

I know the answer has already been accepted, but using display: none; will be a nightmare to users without Javascript.

Using inline Javascript, you can hide an element without it ever blinking. Users without Javascript will still be able to see it.

Consider a few divs that should be hidden when the page loads.

<head>    <script type="text/javascript" src="jQuery.js"></script></head><body>    <div id="hide-me">        ... some content ...    </div>    <script type="text/javascript">        $("#hide-me").hide();    </script>    <div id="hide-me-too">        ... some content ...    </div>    <script type="text/javascript">        $("#hide-me-too").hide();    </script></body>

The inline Javascript will run as soon as the element is rendered, thus hiding it from the user.


I agree with Boris Guéry, that it is not over-engineering, but rather, a standard best practice. I would go a slightly different way than Boris, by adding a no-js class to the html initially and then removing it with JavaScript.

This way you're not waiting for the document to be ready to hide the content, and without any JavaScript you still see the content. Assuming the user has not JavaScript is more in line with the philosophy of progressive enhancement.

ex:

<html class="no-js"><body><div id="foo"></div></body></html>

my css :

#foo {    display: none;}html.no-js #foo {    display: block;}

and javascript

$(document).ready(   function()   {     $('html').removeClass('no-js');   });

********* OR on a per-case basis***********

ex:

<div class="no-js" id="foo">foobar and stuff</div>

css:

.no-js {  display:none;}#foo {  display: block;}#foo.no-js {  display: none;}

js:

$(document).ready(function(){  // remove the class from any element that has it.  $('.no-js').removeClass('no-js');});


I usually set a .js class to my element to set the proper property when javascript is enabled.

I then can set the CSS depending on if javascript is present or not.

ex:

<html class="js"><body><div id="foo"></div></body></html>

my css :

html.js #foo{    display: none;}

and javascript

$(document).ready(   function()   {     $(html).addClass('js');   });