javascriptjqueryouterheight

Measuring height of an off page element


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?


Solution

  • 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();
        })
    }