1

I have tried to get the clientWidth value to know the width of the body. But I found a question:

Below is the original code:

<input type="text" id="width"><br/>
<input type="text" id="height">
<script>
function getScreenSize(){
    document.getElementById("width").value= document.body.clientWidth;
    document.getElementById("height").value= document.body.clientHeight;
}
getScreenSize();
</script>


<div style="margin-top: 5300px;">foot</div>

And when I only change getScreenSize(); into setInterval("getScreenSize()",10);, like below:

<input type="text" id="width"><br/>
<input type="text" id="height">
<script>
function getScreenSize(){
    document.getElementById("width").value= document.body.clientWidth;
    document.getElementById("height").value= document.body.clientHeight;
}
setInterval("getScreenSize()",10);
</script>


<div style="margin-top: 5300px;">foot</div>

Without any reason, the value of clientWidth changed.

Does anyone know why it changed just because I set the setInterval function?

Banana Code
  • 667
  • 1
  • 7
  • 23

2 Answers2

3

This happens because without the setInterval, your script runs before the div at the bottom is added.

So when the browser reads your page, it runs the script and afterwards adds the bottom div, at the moment of run the width and height don't account for the div. With the setInterval, it accounts for that div.

Moving the script to the bottom will present same response from both ways.

<input type="text" id="width"><br/>
<input type="text" id="height">
<div style="margin-top: 5300px;">foot</div>
<script>
function getScreenSize(){
    document.getElementById("width").value= document.body.clientWidth;
    document.getElementById("height").value= document.body.clientHeight;
}
getScreenSize();
</script>
AlexD
  • 3,391
  • 5
  • 32
  • 58
0

Your script is likely running before the page is completely rendered, thus the size of the page can actually change. You need to insure that your code runs after the DOM (Document Object Model) is done (see window.onload vs $(document).ready() for more info).

Community
  • 1
  • 1
John Hascall
  • 8,682
  • 4
  • 46
  • 64