The Javascript DOM17. Attaching Event Handlers |
|
Join the DiscussionThere are a number of disadvantages to hard coding calls to event handlers from within the HTML itself. These disadvantages include the fact that it jumbles the Javascript and HTML together making each harder to maintain and that you can only have one event handler for each event type attached to any one part of the page.There are other disadvantages as well but these two are sufficient to make it worth looking for a better way to attach events to our page. Let's start by looking at how we can separate out the Javascript from within our HTML. The first thing we need to do is to work out what the Javascript event handlers are that we are talking about. When you see an HTML tag that tag has a number of attributes. Some of those attributes are HTML attributes while others are Javascript. We can easily identify the Javascript ones because they all start with on for example: onclick, onkeypress, onload etc. What we want to do is to take these Javascript calls out of our HTML and add the event handlers from within the Javascript. We can of course do this using the DOM access techniques that we already looked at in earlier tutorials. If we give the tag that we want to add event handlers an id then we can use that id to add the event handler into the tag. For example we can replace the event handler in:
<span id="mytag"
onclick="mytagclick();>
with the following in our external Javascript:
function init() {
document.getElementById('mytag').onclick = mytagclick; } window.onload=init; This takes care of the separation of the Javascript event handlers from the HTML but still only allows us to attach one event handler of each type to each object on the web page. This still leaves us with problems if we want to combine two or more scripts together that need to use the same event handler to run different code. The Document Object Model actually offers us far more powerful ways of handling events than the simple and limited way that can be done either by hard coding the events into the HTML or by extracting those event handlers the way that we have looked at here. We'll look further at that in the next few tutorials. |

