1

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
George Duckett
  • 31,770
  • 9
  • 95
  • 162

2 Answers2

1

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();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    How can I do that while being invisible to the user? Could I add them with a left of -1000 then query the height then move them where I want for example? (without any timers etc?) – George Duckett Oct 16 '12 at 08:21
  • +1 So, given the OP's requirement how could he calculate *what the height would be* without adding the element to the page? – El Ronnoco Oct 16 '12 at 08:22
  • @ElRonnoco: Doesn't work, guess I need a callback to allow the layout to refresh. – George Duckett Oct 16 '12 at 08:26
  • 3
    @GeorgeDuckett: You can add the elements to the page, get their height, and remove them. That way they will go through the layout process, but the UI will not be updated to show the element before it's gone. Example: http://jsfiddle.net/Guffa/gnz64/ – Guffa Oct 16 '12 at 08:33
1

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();
    })
}
kayen
  • 4,838
  • 3
  • 19
  • 20
  • I just tried adding to an existing element but couldn't query the height straight after, I guess a timer/callback is needed. – George Duckett Oct 16 '12 at 08:30
  • Updated my code to add an `outerHeight` function which gets executed only after all the `posts` have been appended to the container. – kayen Oct 16 '12 at 08:38