How to run a JS function on a content element when the page is loaded?

I’ve written a JavaScript function which does some stuff to the content of another element. For debugging I ran it from onclick, for example:

 <span onclick="xyz(this)">abc</span>

Once it was working, I wanted to call it when the page finished loading:

 <span onload="xyz(this)">abc<span>

Surprise! It did nothing. The function was never called.

I looked up onload and found that it’s supported by <body>, <frame>, <script>, and a few other tags, but not by <span>.

That kind of makes sense to me, but… now what? Content tags like <span> don’t seem to have any event that is fired when a page is loaded. How can I get that result?

Hey Orthoducks,

If you want some JS to run once the page has finished loading, just put it in a script tag before the closing </body> tag, like this:

        <script src="js/myscript.js"></script>

Thank you for trying to answer my question, but it’s not clear to me how that would work. If I put the function call in open code in a <script> block, it’s no longer in the element that the function is supposed to operate on, and xyz(this) becomes meaningless.

I could make the code work by changing the argument from this to something like document.getElementById(“Item_27”), where a bunch of elements in the page are labeled id=“Item_1”, id=“Item_2”,… id=“Item_27”,… but that would a very ugly (and clumsy, and error-prone) solution!

What does your code do to the <span> elements? One option would be to grab a reference to the containing element and then loop over the children, but this only works if all the <span>'s are together in the page. Another option would be to add a class to all the target elements to allow you to select them. Either way, it’s preferable to avoid attaching event handlers directly in your HTML.

The purpose of the code is to resolve references to items in a numbered list; that is to replace a placeholder with the number of a designated item.

What I ended up doing is a lot like what you suggested. The reference now looks like this:

If the user is already defined, go to step <span class="xref">UserDefined</span>.

To define the cross-reference target:

<li id="UserDefined">...</li>

At the end of the body:

<script type="text/javascript"> resolveXrefs(); </script>

I didn’t want to have the extra bit of JavaScript stuck at the end of the body, but it makes the cross-references simpler.