Measuring height of an off page element

115 views Asked by At

I'm Ajaxing in elements. I want to decide where to put them based on their height (think box-packing type algorithm).

When I loop through my elements as such, I always get 0 for the outerHeight:

posts.each(function(i, e) {
    var elementHeight = $(e).outerHeight();
    // elementHeight is always 0
});

How can I get the display height of my element?


It appears I have to add the element to the page to get the height, which makes sense.
What's the best way of doing this while being invisible to the user as simply as possible?

2

There are 2 answers

2
kayen On BEST ANSWER

Append the posts to a hidden (display: none) div element and then iterate over them to get their respective outerHeight values.

HTML

<div id="postContainer"></div>

CSS

#postContainer { display: none;}

JS

var cont = $('#postContainer'), postsLength = posts.length;
posts.each(function(i, e) {
    cont.append(e);
    if (!--postsLength) calcOuterHeight();
});

function calcOuterHeight(){
    cont.find('.posts').each(function(i, e){
        var oh = $(e).outerHeight();
    })
}
4
Guffa On

You have to add the elements to the page so that they go through the layout process, then they will have a size.

You can add them to the body, get the height, and then remove them. As the browser is busy running your code while the elements are in the page, the elements will never show up:

var el = $('<div>test</div>');
$(document.body).append(el);
var h = el.height();
el.remove();