Dynamically change div height with window resize

Kishore picture Kishore · Jul 18, 2013 · Viewed 19.4k times · Source

I wanted to change height of a div when window is resized. I know it can be done with css using height:100%; but that doesn't work on what i need. I wanted to make this happen in pure javascript without JQuery or any other framework.

Here is what i have done:

<div id="left">
<div id="inner">

</div>
</div>

CSS

#left{

margin-top:40px;
width:200px;
height:576px;
background:white;

}
#inner{

height:100%;
overflow-y:scroll;
}

JAVASCRIPT

window.onload=
window.onresize=function(){
var left=document.getElementById('left');
var window_height = window.innerheight;
if ( window_height > 600px ) { left.style.height = document.body.offsetHeight
+"px";    } 
else { } 
} 

The div with id left has to have the same margin. I just wanted to change the height of div to match the inner window height (in px no %).

Thank You.

Answer

T.J. Crowder picture T.J. Crowder · Jul 18, 2013

window.innerheight should be window.innerHeight (capital H). Note that IE doesn't support it prior to IE9.

Also note that you're comparing an element with a number here:

if ( left < window_height )
//   ^--- element

You probably wanted to get the height from left instead, as that condition will never be true.