Handling events with the DOM – Part I - Back to basics: assigning event handlers
(Page 2 of 4 )
There are two basic ways of assigning an event handler. The first, most used, and certainly obtrusive technique is embedding it directly into the HTML markup, while the second is just including the event handler within the own piece of JavaScript code. Definitely, this last one is the recommended approach, since it allows us to maintain the HTML and the JavaScript pieces residing in different layers, making the code much more flexible and portable.
Let’s illustrate the first approach, inserting the event handler inside its own HTML tag, appending it as a regular attribute:
<a href="http://www.devarticles.com" title="Opens link in a new window" onclick="window.open('http://www.devarticles.com');return false;">Click here for great Web Development articles</a>
In the above example, we’ve embedded the event handler along with the JavaScript code to be executed. As we can see, the HTML markup is rather dirty using the inline approach. Now, let’s implement the same functionality, this time by inserting the event handler within the JavaScript code. Like this:
<script language="javascript">
openLink=function(){
var devlink=document.getElementById('devlink');
devlink.onclick=function(){
window.open('http://www.devarticles.com');
return false;
}
}
window.onload=openLink;
</script>
And rewriting the HTML markup, in the following manner:
<a href="http://www.devarticles.com" title="Opens link in a new window" id="devlink">Click here for great Web Development articles</a>
An explanation is in order here. In this second example, we’ve built a completely separate script, inserted the "onclick" event handler within the "openLink()" function, and then executed the script when the page is loaded (utilizing "onload", another event handler). Note how we have dynamically attached a new function to the link, without the need of declaring the function name. Undoubtedly, this last technique is much better and cleaner than the first one.
Now we’ve grasped the general concept for assigning event handlers. Having explained the two conventional ways to assign event handlers, let’s go one step further and learn a little more about the manner the DOM handles events.
Next: Understanding the DOM event flow: Event Capture and Event Bubble >>
More JavaScript Articles
More By Alejandro Gervasio