In this first article in a three part series, you will learn several of the methods that the Document Object Model offers for capturing and handling events that happen within the context of a Web document.
Handling events with the DOM – Part I - Back to basics: assigning event handlers (Page 2 of 4 )
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>
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.