Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide elements with jQuery before they get rendered?

I want to generate html layout with areas (divs, spans) that can be shown/hidden conditionally. These areas are hidden by default.

If I call .hide() method with jquery on document.ready these areas may blink (browsers render partially loaded documents). So I apply "display: none" style in html layout.

I wonder what is the best practice to avoid blinking, because applying "display:none" breaks incapsulation rule - I know what jquery does with hide/show and use it. If jquery's hiding/showing implementation will change one day, I'll get the whole site unworkable.

Thank you in advance

like image 439
Andrew Florko Avatar asked May 10 '10 07:05

Andrew Florko


People also ask

How do we hide content in jQuery?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page).

Which jQuery method is used to hide elements?

The hide() is an inbuilt method in jQuery used to hide the selected element. Syntax: $(selector). hide(duration, easing, call_function);

Can be used in jQuery to hide and display an element of HTML?

jQuery toggle() You can also toggle between hiding and showing an element with the toggle() method.


1 Answers

@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.

like image 114
Marko Avatar answered Sep 18 '22 09:09

Marko