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.
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):
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With