JS - set window height using current window size

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

I did some code of this kind of work - it calculates the height of the window, but does not change the height of the body. What am I doing wrong?

function setWindowHeight(){ var windowHeight = window.innerHeight; document.getElementsByTagName('body').style.height = windowHeight + "px"; } 
+4
source share
2 answers

You need to add eventListener, and you do not need to use getElementsByTagName, because it has only one 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 code above): you can check the value in the Firefox console. Open it (CTRL + SHIFT + K) and resize the window, you will see that resizing the event will be triggered when you do this.

+5
source
 try this may work document.getElementsByTagName('body').height = windowHeight + "px"; 
-1
source

All Articles