Might seem like a trivial question but I've run into an issue while using jQuery. When I try and get the height for an element within a .ready I am always given zero.
$(function() {
$('#my-elem').height() // Always gives me zero.
});
If I put code in a delay with setTimeout() around the height check (say of .5s) then the height is correctly reported back to me. I'm guessing that this is because the styles haven't had a chance to be applied yet?
The only solution I've found to this problem is to use an interval to poll the height of the element until it becomes non-zero but this seems overkill to me. Is there a better way?
The document.ready
event signals that the HTML DOM is ready for accessing via Javascript, but that doesn't mean that the elements have already rendered.
In fact, that's the whole shebang behind ready
: it's a means for you to start manipulating your document's HTML DOM without having to wait for the page to finish loading. It's safe to assume that at document.ready
, your elements are not yet displayed on the page.
Now, that comes with a caveat: if the elements haven't rendered yet, how can the browser / Javascript know what its resolving height is? .height()
may give zero at document.ready
because of this. It's probably best to wait until load
instead of ready
when it comes to pulling box dimensions from the layout.
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