javascripthtmldatetimeconcatenation

How to trigger inline script onload?


I have the following script, as seen, it calls the Date method onClick event, like so:

<!DOCTYPE html>
<html>

<body>

  <p onclick='this.innerHTML = Date();'>click me!</p>


</body>

</html>

How can I do the same with an onLoad event? I don't want to define it with a separate <script> tag and call it as a function. I'd like the most minimal coding. Why doesn't the following work?

<!DOCTYPE html>
<html>

<body>

  <p onload='this.innerHTML = Date();'>date here onload</p>


</body>

</html>


Solution

  • body tag of html has onload function.

    The onload event occurs when an object has been loaded.

    onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

    The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

    I am not sure if this is recommended.

    Here, you can do like this.

    <body onload="document.querySelector('#date-container').innerHTML = Date()">
      <p id="date-container"></p>
    </body>

    Hope, this helps.