DevonRyder
DevonRyder

Reputation: 193

Why does the event handler in the <h1 onload> attribute not run?

I'm playing around with Javascript to get back in the swing of things for my second semester web class that recently started, and I've run into an issue getting getElementById and innerHTML to work.

Basically, I want to populate an empty h1 with an Animal name

function favAnimal()
      {
         document.getElementById("animal").innerHTML="cat"
      }
<h1 id="animal" onload="favAnimal()">Favourite Animal Placeholder</h1>

The above does not change anything. If the h1 is empty the result is the same. I've also tried with a <div> to rule out an issue using specific elements.

All help is appreciated and thanks in advance!

Upvotes: 0

Views: 644

Answers (3)

jfriend00
jfriend00

Reputation: 708116

An <h1> tag does not have an onload event handler so your function is never being called.

You can use the onload handler for the <body> tag or set up some other event handler to assign your function to.

If you want your code to be triggered when the document is loaded, you can use one of these:

window.addEventListener("load", favAnimal);       // all page resources loaded
document.addEventListener("DOMContentLoaded", favAnimal);   // HTML done parsing

If you just want your script to be executed right after your <h1> tag has been loaded, you can just place a call to the script right after the tag. The page is parsed/executed in order so that any script will always be able to reference HTML elements that come before it in the document:

<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>

Here are some of the things I'm aware of that have a load event:

window
<img>
<body>
<iframe>
<link>
<script>
<embed>
<object>
<video>
<audio>
XMLHttpRequest

And, pretty much any other HTML tag that has a src or href attribute except <a>. The idea is that if the tag is loading some external resource, then there is a load event to know when it is done loading that external resource. If the tag is not loading an external resource, there is probably not a load event for it.

Upvotes: 3

Oriol
Oriol

Reputation: 288680

The load event is only dispatched on resources, such as the document, images, ...

If you want to run some script just after an element has been parsed, just add a script element after it:

<script>
  function favAnimal() {
    document.getElementById("animal").innerHTML = "cat";
  }
</script>
<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>

Upvotes: 2

navtej singh
navtej singh

Reputation: 277

What is happening here that ur script file executed earlier than the html renders. So it is not able to locate the element as it is not rendered yet. Browser provides events like onload ,unload. Here u need onload `Document.addEventListener("DOMContentLoaded",init);

Function init (){ //ur code }`

Upvotes: -2

Related Questions