1

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>

5
  • 2
    <p> elements don't have an onload event. Commented Nov 16, 2024 at 14:41
  • @GuyIncognito So, how to circumvent that? Commented Nov 16, 2024 at 14:43
  • 1
    Give the element an id, attach a handler to the window's onload event, and change the element contents by referring to it by the id Commented Nov 16, 2024 at 14:46
  • 1
    Does the script have to be inline? It's generally not a very good practice to do that. Put the logic in to a function, then call it on the click event handler of your p element and also on DOM ready Commented Nov 16, 2024 at 19:42
  • @RoryMcCrossan after all the responses including yours, I say it doesn't have to be inline, and I agree with you. Thank you for your comment. Commented Nov 16, 2024 at 20:26

1 Answer 1

3

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.

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

3 Comments

Supported HTML tags: <body>, <frame>, <frameset>, <iframe>, <img>, <input type="image">, <link>, <script> and <style> For further info: w3schools.com/tags/ev_onload.asp
These are GlobalEventHandlers, yes it is not so much recommended, as proof MDN removed the page from their docs, but here is a mirror link. We do have to use eventListeners instead, for some reasons, but all this will work for a long time or it will break the internet. devdoc.net/web/developer.mozilla.org/en-US/docs/Web/API/…
Better to set the textContent or innerText property since the text being assigned is not markup. Reasonably safe here, but not in general when assigning text as element content. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.