Skip to content Skip to sidebar Skip to footer

Javascript Element Offsetheight Returns Returns 0 In For Loop

I am trying to dynamically get the height of a child element inside a three column grid. When i is equal to 2 or when i is greater than 1 (i.e. when there are at minimum 2 elements

Solution 1:

When there is only 1 element inside the loop, blocks.length will only be 1. Therefore, when your for loop starts, the condition i<blocks.length is already false, because i is also equal to 1. Declare var i = 0 in the for loop. Hope this helps!

Solution 2:

improved the code, check it out: https://jsfiddle.net/0otvhgkg/8/

functionrenderGrid(){
var blocks = document.getElementById("grid_container").children;
var pad = 0, cols = 3, newleft
var newtop = 0var max_height = blocks.length ? blocks[0].offsetHeight : 0;

    for(var i = 1; i < blocks.length; i++){
        if (i % cols == 0) {
            newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;     
          blocks[i].style.top = newtop+"px";
          max_height = Math.max(max_height, newtop + blocks[i].offsetHeight);
        } else {
            if(blocks[i-cols]){
                newtop = (blocks[i-cols].offsetTop + blocks[i-cols].offsetHeight) + pad;
                blocks[i].style.top = newtop+"px";
                max_height = Math.max(max_height, newtop + blocks[i-cols].offsetHeight);
            }
            newleft = (blocks[i-1].offsetLeft + blocks[i-1].offsetWidth) + pad;
            blocks[i].style.left = newleft+"px";
            max_height = Math.max(max_height, newtop + blocks[i-1].offsetHeight);
        }
  }
    $('#grid_container').css('height', max_height);
}
window.addEventListener("load", renderGrid, false);
window.addEventListener("resize", renderGrid, false);

Problem was we calculated max_height only when new row was created and didn't care about the first row whatsoever.

Post a Comment for "Javascript Element Offsetheight Returns Returns 0 In For Loop"