0

This might be a very stupid question for some people, but I surely am not able to understand the problem behind this. The code is fairly simple, and goes as follows:

HTML:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>####</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="css.css">
    </head>
    <body onload="resizeDiv();">    
        <div id="testElement">ABCD</div>
        <div id="secElement">ABC</div>
        <script type="text/javascript" src="javascript.js"></script>
    </body>
</html>

CSS:

html , body{
    height:100%;
}
#testElement{
    background-color:black;
    color:white;
}
#secElement{
    font-size:50px;
}

JS:

(function immediate(){
    document.getElementById('secElement').textContent = window.innerHeight;
}());
function resizeDiv(){
    document.getElementById('testElement').style.height = (window.innerHeight - 50) * 0.9;
}

Now, by this code, the div with id 'testElement' should have an height which is 90% of the window.innerHeight - 20. But, nothing seems to work. Please help.

codetalker
  • 576
  • 1
  • 6
  • 21
  • You have to wrap the JS in a handler like window.onload(function{}) for the ready or loaded events. When your JS is executed right now, the element doesn't yet exist. – Bennett Brown Oct 31 '15 at 16:54
  • @BBrown, I tried to include the function in window.onload, but still no response – codetalker Oct 31 '15 at 17:00

3 Answers3

1

body tag has a onload handler assigned to resizeDiv() but your script is at the bottom of the page so, the onload handler can't refer to it.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

Use document.getElementById('testElement').setAttribute("style","height:" + (window.innerHeight - 50) * 0.9) + ' px'; You can find more explanation why to use it here: Setting DIV width and height in JavaScript

Community
  • 1
  • 1
mic4ael
  • 7,974
  • 3
  • 29
  • 42
1

Add "px":

document.getElementById('testElement').style.height =  (window.innerHeight - 50) * 0.9 + "px";
brooksrelyt
  • 3,925
  • 5
  • 31
  • 54
Sudipta Kumar Maiti
  • 1,669
  • 1
  • 12
  • 18