Skip to content

CategoryHTML

Assigning Handlers on Load

Rather than assigning event handlers to elements inline from within HTML, like so:

<a id="site" href="http://www.shinylight.com">Go to my site!</a>

You can assign the event handler programmatically via the onload event of the window object. Like so, in the script element:

window.onload = function() 
{
  document.getElementById("linkcontent").onmouseover = Show;   
}

function Show( )
{  
  alert( "Hey there, how are you?" + this.href );
}

Here’s the HTML:



<div id="content">
  <a id="linkcontent" href="http://www.shinylight.com?var=yes">This is pretty cool</a>
</div>  



This is just a great way to keep HTML code away from JavaScript. In this case, the handler for window.load will run when all web page resources have finished loading (the full HTML and JavaScript files).