JS - set window height using current window size

29,906

You need to add an eventListener, and you don't need to use the getElementsByTagName because has only 1 body tag:

function setWindowHeight(){
    var windowHeight = window.innerHeight;
    document.body.style.height = windowHeight + "px";
    console.log(document.body.style.height);
}
window.addEventListener("resize",setWindowHeight,false);

Or, if you want to use, you can do this:

function setWindowHeight(){
    var windowHeight = window.innerHeight;
    document.getElementsByTagName('body')[0].style.height = windowHeight + "px";
    console.log(document.body.style.height);
//---------------------------------------´
//will get the first element tagged body
}
window.addEventListener("resize",setWindowHeight,false);

EDIT (Changed the code above): you can check the value in the Firefox Console. Open it(CTRL + SHIFT + K) and resize the window, you will see the event resize be fired when you do it.

Share:
29,906
cloggy
Author by

cloggy

Updated on October 12, 2020

Comments

  • cloggy
    cloggy over 3 years

    I have some CSS that needs the body to have a height set, but this needs to be done depending on the user.

    I have made some code that kind of works - it calculates the window height but it's not changing the body height. What am I doing wrong?

    function setWindowHeight(){
        var windowHeight = window.innerHeight;
        document.getElementsByTagName('body').style.height = windowHeight + "px";
    }
    
  • cloggy
    cloggy over 11 years
    Thank you Erick! Much appreciated. I'm trying to learn JS but this was a bit beyond me.