Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery finding the total height of all divs children

hey I have a div with 5 div's contained in it, I want to add all of their heights together,

This is the solution I ended up using based off of Jeff's answer. Thanks for helping me out.

var ev_totalHeight = 0;
$("#events > div").each(function(){
    ev_totalHeight += $(this).innerHeight();
});



function events_open() {
 $("#events").animate({
"height": ev_totalHeight
  }, 450 );
}

$("#events").click(function() {
events_open();
});
like image 529
loriensleafs Avatar asked Oct 24 '12 11:10

loriensleafs


Video Answer


2 Answers

Heres a fiddle: http://jsfiddle.net/yj8sL/2/

$(function(){
    var totalHeight = 0;
    $("#parent > div").each(function(){
        totalHeight += $(this).height();
    });
    alert("Total height of all divs: "+totalHeight);
});

As you see, there are 5 divs, with a height of 100px each, so the total height is 500px.

EDIT: Your next problem (with the animate) is that you are not telling it what unit you are using (in your case, pixels):

 $("#events").animate({
    "height": ev_totalHeight+"px"
 }, 450 );
like image 106
Jeff Avatar answered Oct 10 '22 16:10

Jeff


Something along these lines:

var height = 0;

$('#events > div').each(function(){
    height += $(this).height();
});

// apply calculated height to another element
$('#myotherdiv').height(height + 'px');
like image 44
Paul Fleming Avatar answered Oct 10 '22 16:10

Paul Fleming