1

I am beginning to program. In the bottom code, when run, will completely refresh the page. How can I avoid this? Thank you very much for your time!

<h1>Space Calculator Demo</h1><br> If you were to start a trip at
<script type="text/javascript">
  function printTime() {
    var d = new Date();
    var hours = d.getHours();
    var mins = d.getMinutes();
    var secs = d.getSeconds();
    document.body.innerHTML = hours + ":" + mins + ":" + secs;
  }
  setInterval(printTime, 1000);
</script>
<div id="time"></div> , how long would it take you and how much food and water would you need?

3
  • 1
    It does not refresh the page, but you set the html of the whole body document.body.innerHTML to the text. Commented Jul 26, 2017 at 17:57
  • 1
    It doesn't refresh you page, it just overrides the complete html. The selector for document.body.innerHTML just has to be: document.getElementById('time').innerHTML, example Commented Jul 26, 2017 at 17:57
  • or how to change text value within an element?, Replace only text inside a div using jquery Commented Jul 26, 2017 at 17:58

3 Answers 3

2

The page isn't refreshing, you were setting the entire body of the page equal to your time. Instead of setting body, set time.

<h1>Space Calculator Demo</h1><br> If you were to start a trip at
<script type="text/javascript">
  function printTime() {
    var d = new Date();
    var hours = d.getHours();
    var mins = d.getMinutes();
    var secs = d.getSeconds();
    document.getElementById('time').innerHTML = hours + ":" + mins + ":" + secs + ",";
  }
  setInterval(printTime, 1000);
</script>
<div id="time"></div>How long would it take you and how much food and water would you need?

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of rewriting the body, use document.getElementById('time') and set the text of that element only

Comments

1

By assigning to document.body.innerHTML, you are overwriting all content on the page. document.body refers to the entire page, so setting is HTML erases everything that was there before (your header, div, and text).

It looks like what you want to do is only change the contents of <div id="time"></div>. For that, you should change the line

document.body.innerHTML = hours + ":" + mins + ":" + secs;

to this:

document.getElementById('time').innerHTML = hours + ":" + mins + ":" + secs;

This will overwrite only the contents of your div, leaving the rest of the page intact.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.