Get calculated height - Javascript - not jQuery

I have two divs side by side set to auto. I want them to be of equal height, so I combined them as elements of an array.

I recursively scan the array and set not the tallest to the height of the tallest. The problem is that I tried to get COMPUTED height, which led to the wrong value.

I tried the following:

(els[x].currentStyle) ? h=els[x].currentStyle.height : h=window.getComputedStyle(els[x],null).height;

h =  el.clientHeight || el.offsetHeight || el.scrollHeight;

Both of them give 640 px'ish, while in my particular display, 751.8 is calculated.

Could there be a constant that I can use to get the correct height. How, maybe, the number im getting will be on a standard-sized screen (for example, 960 pixels in height or so), and then somewhat in size of the window?

+4
source share
1 answer

I had a lot of good use of this little function that I came up with

function getH(id)
{
    return document.getElementById(id).offsetHeight;
}
// I have a styles.js file where this function feels right at home. Access this function from anywhere.

This will return the height of any given elements given to the function (by its identifier). So now we are on 1/3 of the way.

Then use the Math.max () function to get the height of the largest element.

var maxH = Math.max(getH("ID1"),getH("ID2")); 

This is 2/3 of the way, YAY - now set the height of the elements to the same.

var x = document.getElementById("ID1");
var y = document.getElementById("ID2");

x.style.height = maxH +"px";
y.style.height = maxH +"px";  //Remember the +"px" has to be added as a string, thats the reason for the "".

DONE !! - Now all together

I would suggest something like this

function setElementHeight()
{
    var maxH = Math.max(getH("ID1"),getH("ID2"));
    var x = document.getElementById("ID1");
    var y = doc...("ID2");
    x.style.height = maxH +"px";
    y.style.height = maxH +"px";
}
// Don't forget to include the first function in you'r .js file

This will set both IDs to the same height, and the height will be equal to the highest. This is what you want, isn't it?

- EDIT -

I would select an array if I were you. Just have 2 DIVs each with a unique identifier and make them equally tall based on this.

  • Molle
+6
source

All Articles