I have a javascript function that manipulates the DOM when it is called (adds CSS classes, etc). This is invoked when the user changes some values in a form. When the document is first loading, I want to invoke this function to prepare the initial state (which is simpler in this case than setting up the DOM from the server side to the correct initial state).
Is it better to use window.onload to do this functionality or have a script block after the DOM elements I need to modify? For either case, why is it better?
For example:
function updateDOM(id) {
// updates the id element based on form state
}
should I invoke it via:
window.onload = function() { updateDOM("myElement"); };
or:
<div id="myElement">...</div>
<script language="javascript">
updateDOM("myElement");
</script>
The former seems to be the standard way to do it, but the latter seems to be just as good, perhaps better since it will update the element as soon as the script is hit, and as long as it is placed after the element, I don't see a problem with it.
Any thoughts? Is one version really better than the other?
Edit: Thanks for the answers guys! Both makes sense, but unless a better answer comes along, I'm going to accept John Millikin's answer because I like the separation of logic and view.
Further Edit: Thanks for all the new good answers! Thanks for all the library suggestions, and all the great ideas! However, that was not my intent in the question, as I already use a library (we use MochiKit at work, which I like because it adds a strong functional flavor to JavaScript). I didn't think of it while writing my example, but I do normally hook up events via a library, and I fully agree with all the arguments below for using them. I was most interested in whether the idea of using an onload vs a script block after the element was the way to go, and I still believe the answer I accepted first best sums up why onload is better (sorry to all the great posters that came later! too bad I can't accept more!). Thanks again!