Reputation: 1127
I have a box with fixed width (800px) that is filled with contents from nicEdit.
I need to know the height of the contents that are put inside the box, if I count the number of rows it will not work with long texts or with images or different font sizes...
I need to find the height to set the box with an height that will not show scrollbars and will not be higher than the content.
<div style="width: 800px; overflow: hidden"><?= $contentbyuser; ?></div>
This "page" will be shown into an iFrame with a code like:
<iframe style="width: 800px;height:???px;" src="page.php"></iframe>
How can I find the height to set to the iframe with javascript and/or jQuery?
Upvotes: 0
Views: 80
Reputation: 76003
You can create a dummy element, insert the HTML into it, and then check its height.
//create dummy
var $dummy = $('<div />').css({ position : 'absolute', left : -9999, width : 800 }).html(randomTextandImages);
//add dummy to the DOM
$("body").append($dummy);
//get the height of the dummy
var theHeight = $dummy.height();
//at this point we can remove the dummy from the DOM
$dummy.remove();
//set the height of the iframe
$("iframe").height(theHeight);
Be aware that the dummy element should have the same CSS applied to it as your regular container, so that it will render the same. Font properties are particularly important (e.g. font-size, font-weight, line-height, etc.).
Setting the position to absolute
and giving a large negative left property means this will occur off-screen, so the user won't see it happen.
Also, I can't remember if I'd had an issue with this in the past, but if you're getting a height of zero then the code that gets the height of the dummy should be put in a short timeout so the dummy can render before getting its height.
Upvotes: 1
Reputation: 2289
Set the height of the div to be automatic based on the content. Then you can do this in your JavaScript:
$("div").html(randomTextandImages);
var height = $('div').height(); // Give this to whoever will be using the iframe
Upvotes: 0