Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading