Javascript DOM offsetHeight issue on small screens

1.3k views Asked by At

I have a simple code to set the height of one column, id="colLeft" to the height of another column, id="colRight", with no padding or borders:

<script type="text/javascript">
    var colLeft = document.getElementById("colLeft");
    var colRight = document.getElementById("colRight");
    colLeft.style.height = colRight.offsetHeight + "px";
</script>

This code works fine on desktop and iPad, but on my android phone the results are rather unpredictable. Sometimes colLeft is much longer, sometimes colRight, and sometimes it works the way it should. I have tried it on two browsers with the same results.

I have also tried it inside window.onload=function(){...} which gave slightly less variance in the results, but is still not perfect.

Thanks for any help.

1

There are 1 answers

0
Warren R. On

You can read a bit about offsetHeight here. The important thing to note is that if the content is larger than the viewable area the browser might do funny things with non-scrolling elements. Because this is a phone browser, I am guessing that the issue is that it is miscalculating the column height because it doesn't deal with scrolling elements correctly.

How do you set the height of the first column? If it has a valid height set in the style sheet you could easily do something like this:

colLeft.style.height = colRight.style.height;

If that doesn't work, you may need to set the column height based on the browser window size with something like:

    colLeft.style.height = colRight.style.height = (window.innerHeight - 10) + "px";

Or something similar.