0121 31 45 374
Qoute Icon

Stop jQuery.hide() showing the elements on page load

Tim

This is a great little tip that Andy Higgs shared with me a couple of months ago while we were developing Crisis Cover. If you write jQuery that hides the div when the user has JavaScript enabled, you can avoid the divs all being shown while the page loads by simply adding a class to the body of the page using jQuery and hide it using CSS like so:

<html>
<head></head>
<!-- Reference to jQuery here -->
<body>
<!-- This should be the first bit of code and don't wait until the page has loaded -->
<script type="text/javascript">$('body').addClass('js');</script>
<!-- The rest of your code here -->
<div class="jsHide">
	<p>This paragraph is hidden if the user has JavaScript enabled.</p>
</div>
</body>
</html>

 

Then you just need to add the css:

.js .jsHide

Your divs will now be hidden until you show them with JavaScript. Nice, simple solution to an ever annoying problem.

Note: For my demo to work you'll need to include jQuery

Update: As pointed out by Petr below and Andy Higgs/Trevor Morris, it would be better to target using JavaScript without jQuery and target the body for maximum flexibility (note the space at the front in case there is already a class):

<script type="text/javascript">document.getElementsByTagName('html')[0].className+=' js'</script>

Liked this post? Got a suggestion? Leave a comment