Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to determine a DIV's height before visible on the webpage?

I have a script that will fetch data from server and compose a DIV according to it. The DIV will contain image, text and other undetermined content. I want to arrange it freely, so I need to know its height and width before it is shown to the user.

But per my understanding, I should ask browser to render it firstly, otherwise I can't know the width&height.

Is there any best way to know a DIV's width&height without showing it to user?

EDIT:

Some good guy suggests that I use jquery's .width() method, but I am wondering that if the DIV contains image, will jquery wait after the image is downloaded? I don't know the image's dimension beforehand.

like image 572
Bin Chen Avatar asked Dec 20 '11 11:12

Bin Chen


1 Answers

You can set display: none style on the div. Then use .width() from jQuery and you will get this value.

For the duration of the calculation it will use .swap() to set style so element is visible, call callback calculating the width and swap style back.

It will set (see the code):

  • position: absolute
  • visiblity: hidden
  • display: block

EDIT (see comments):

If you are loading a image and you want to make sure the image is loaded before you calculate the width then you can attach width calculation as the onload handler like this:

$('#someImg').load(function() { 
  // image is loaded, you can calculate the width
  console.log($('#test').width())); 
});

HERE is a working example.

like image 104
kubetz Avatar answered Nov 15 '22 03:11

kubetz