Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Hide a Div at startup (load)

I have a div in my php page that uses jQuery to hide it once the page has loaded. But is there a way to hide it from the very start of loadup?

The reason I ask is because for a brief second, you can see the div when the page is loading, and then hides when the page is fully loaded.

It looks unprofessional.

Just wondering if there is a way around this?

Thanks

like image 690
Oliver Jones Avatar asked Apr 13 '12 21:04

Oliver Jones


People also ask

How do I hide a div when a page is loaded?

Use display none on the element eighter in HTML, or in CSS files.

Can you hide a div in JavaScript?

To hide a div using JavaScript, get reference to the div element, and assign value of "none" to the element. style. display property.

How do I hide a div?

We hide the divs by adding a CSS class called hidden to the outer div called . text_container . This will trigger CSS to hide the inner div.

How do you hide an element in JavaScript?

In JavaScript, we can hide the elements using the style. display or by using the style. visibility. The visibility property in JavaScript is also used to hide an element.


2 Answers

Use css style to hide the div.

#selector { display: none; } 

or Use it like below,

CSS:

.hidden { display: none; } 

HTML

<div id="blah" class="hidden"><!-- div content --></div> 

and in jQuery

 $(function () {      $('#blah').removeClass('hidden');  }); 
like image 80
Selvakumar Arumugam Avatar answered Sep 20 '22 22:09

Selvakumar Arumugam


I've had the same problem.

Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.

In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :

<script>document.write('<style>.js_hidden { display: none; }</style>');</script>

<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>

Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :

  • for non JS users, the div is visible directly
  • for JS users, the div is hidden and has toggle effect.
like image 30
DavG Avatar answered Sep 17 '22 22:09

DavG