0

When I run this, "11" appears on the page immediately followed by "25" followed by 40 <br/> followed by "Finished" so the data written to the page is sort of concatenated. But when I click the button the third document.write() in the writePos() function overwrites everything written outside the scope of the function. Why?

<!DOCTYPE html>
<html>
<body>
<input type="button" onclick="runNavigator()"; value="Run Navigator"/>
<script>
document.write(5 + 6);
document.write(12+13);
for (var i = 0; i<40;i++)
    document.write('<br/>');
document.write("Finished");

function writePos(position) {
    console.log("writePos");
    var map_url="http://maps.googleapis.com/maps/api/staticmap?center="+position.coords.latitude+","+
    position.coords.longitude + "&zoom=12&size=550x400&sensor=false";

    document.write("Latitude: "  + position.coords.latitude + '<br/>');
    document.write("Longitude: " + position.coords.longitude + '<br/>');
    document.write('<br/><div><img src="' +map_url+'"/></div>');
}

function runNavigator() {
    navigator.geolocation.getCurrentPosition(writePos);
}
</script> 
</body>
</html>
Ron
  • 43
  • 1
  • 7
  • 4
    Because that's what `document.write()` does. Once the page is finished, it's "closed", and a subsequent call to `document.write()` causes the page to be "opened" again. Opening a page involves clearing it of all content. – Pointy Oct 12 '15 at 15:49
  • Use the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) to change the HTML of a page with JavaScript. – Reeno Oct 12 '15 at 15:52

0 Answers0