Separating Content from Behaviour.

In the same way we use CSS to separate Content from Presentation to produce simpler HTML we can also separate Content from Behaviour.

The method results in removing all javascript event handlers from the html and only adding it when the page loads.

Button1 Button2

Here is a cut down version of the code for the buttons on this page which demonstrates this approach.

<head>
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<span id='button1' >Button1</span>
<span id='button2' >Button2</span>
</body>

Notice there are no event handlers, such as onclick, in the button span tags.

This results in very clean html code with no inline javascript or function calls to call behaviours.

// external.js
function goodtogo1(){
   alert('Button 1 Clicked')
   return false;
}
function goodtogo2(){
   alert('Button 2 Clicked')
   return false;
}

window.onload=function attachbehaviours(){
   // Format is object.event=function name
   // This registers the function to the objects event
   // Note: The functions we assign have no brackets
   document.getElementById('button1').onclick=goodtogo1;
   document.getElementById('button2').onclick=goodtogo2;
}

This looks like a complicated way to display an alert box.
However it is a method that can be easily extended to allow many events to be attached to various tags.

How Does It Work !

The attachbehaviours() function allows behaviours to be linked via functions to various dom elements.
In this example the input button's onclick event is linked to the goodtogo() function.

document.getElementById('button1').onclick=goodtogo;

This can only be done once document is fully loaded using the window onload event.