skip to Main Content

I am using NGINX. I want to display the current time as an easy way of practicing. I set this in a JavaScript variable. So far, I have a little bit of HTML code.

<!DOCTYPE html>
<html>
  <head>
    <title>???</title>
    <style>
      body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
      }
    </style>
    <script type="text/javascript">
      function myFunction() {
        var d = new Date()
        var n = d.getTime()

        document.getElementById('current-time').innerHTML = n
      }
    </script>
  </head>
  <body onload="myFunction">
    <h1>???</h1>
    <p>This is the current time.</p>
    <p>
      <u>
        <i>
          Current Date and Time is
          <span id="current-time"></span>
        </i>
      </u>
    </p>
  </body>
</html>

I don’t understand why this isn’t working, I have looked in Stack Overflow a lot and this is what they say to do. There are no errors printing in the console, and all the page says is “Current Date and Time is”, and nothing happens with the <span id="current-time">.

3

Answers


  1. Here: <body onload="myFunction"> you just provided function reference without execution.

    You will need to update it to be:
    <body onload="myFunction()">

    with myFunction() parentheses in the end, so your function will be actually executed on onload event.

    Also, from your snipped above, it looks like </body></html> closing tags are missing.

    Login or Signup to reply.
  2. let d = new Date();
      
    let n = d.toLocaleString();
    

    will format correctly
    as well as updating the parenthesis in:

    <body onload="myFunction()">
    
    Login or Signup to reply.
  3. Make <body onload="myFunction" <body onload="myFunction()"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search