abhishek-23
abhishek-23

Reputation: 516

clientHeight not working in JavaScript?

I'm learning JavaScript and created a countdown timer HTML page in which javascript code seems to be returning a wrong clientHeight of the body. I want to show my countdown HTML <div> in middle (vertically) of the body even when browser is re-sized. Please tell me where I am wrong.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CountDown Timer</title>
<script type="text/javascript" >
function countdown(){
    if(isNaN(document.getElementById("time").value))
    {
       document.getElementById("time").value = "Enter Valid Number";
       return;
    }
    else
    {       
       var i = document.getElementById("time").value;
       var j=setInterval(function (){document.getElementById("new").innerHTML = i; i--;
       if(i == -2){
         document.getElementById("new").innerHTML = "Welcome";   
         clearInterval(j);}},1000);
       }
    }

    function heightadjust(){
       document.getElementById("main1").style.top = ((document.body.clientHeight/2)+54).toString() + "px";
    }

</script>
</head>

<body onresize="heightadjust();" onload="heightadjust();">
<div style="margin:0 auto;" id="main1">
   <center>
     <div id="new" style="display:inline-block; padding:3px; font-size:60px; text-align:center; border:3px solid #000000; background-color:#CC3300; color:#FFFFFF; border-radius:6px;">Enter Time Below</div>
     <br />
     <input type="text" id="time" onfocus="this.value = ''; this.style.color = '#000000';" value="Enter Time here" style="color:#999999;" />
     <button onclick="countdown();" >Start</button>
   </center>
</div>

</body>
</html>

Please, give me some tips how to keep <div> vertically centred even if browsers are re-sized.

Upvotes: 1

Views: 1592

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

You don't need JS for that.

#in_the_middle {
  position:fixed;
  left:50%;
  top:100%;
  width:200px;
  margin-left:-100px; /* MUST be equal to width * -0.5 */
  height:50px;
  margin-top:-25px; /* SHOULD equal height * -0.5, but can vary for different fx */
  line-height:50px; /* Remove if there may be more than one line inside */
}

Upvotes: 3

Related Questions