I have a div.
<div id="test">this is a lot of text and more and more and more and more and more and more and more and more text</div>
On document.ready I am getting the height of the div.
$(document).ready(function() {
var intDivHeight = $("#test").outerHeight(true);
});
If I expand my browser window to be very wide so the text does not wrap and reload the page the height is 32. If I shrink my browser window to be skinny so that the text wraps on two or three lines, the height is still 32.
Odd.
If I put the above code in a window.resize function, I get the wrong size on initial page load, but I get the correct size as soon as I start resizing the window.
$(window).resize(function() {
var intDivHeight = $("#test").outerHeight(true);
});
32 changes to something like 56 or 78 on resize.
Odd.
Could someone please explain to me why this happens? And, is there a solution so that I can get the correct "wrapped" height on document.ready? I am using this to try and position certain elements using JavaScript.
Thanks!
You can get scrollHeight
through just plain ol' javascript! Or, if you plan to have overflow content in the div, you can stick to using the jQuery outerHeight()
function, instead.
As far as reporting the numbers on page load vs resize, you'll need to bind 2 event handlers to do so. The first one, on load
, and the second on resize
.
I can make a quick example:
$(function() {
$(window).on("load resize", function() {
console.log("Our height is " + $("div")[0].scrollHeight);
});
});
div {
background-color: #f1f1f1;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text! Look at all this text!</div>