1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Attaching Event Handlers in Javascript

Join the Discussion

Questions? Comments?

The more that you can actually separate your Javascript from your HTML, the easier to maintain that your web pages will be and the easier it will be to reuse your javascripts in multiple pages with minimum work to attach them to the page.

One of the least obvious pieces of Javascript to remove from your HTML are those pieces that don't look like Javascript - the event handlers that are embedded directly into the various HTML tags. These are the 'attributes" within your various HTML tags which start with on. For example:

<a href="page1.htm" onclick="location.href='page2.htm';return false;">

Modern browsers support Event Listeners as an alternative to using event handlers like this and JScript in Internet Explorer supports attachEvent at an equivalent to using event listeners in Javascript but for most purposes converting your code to use those methods of handling the event are somewhat of an overkill where all we want is to attach a simple single event to a single tag.

What we really want to do is to move the onclick (or whatever event handlers we are currently embedding in our HTML) out of the HTML and just call them from our Javascript code instead. We can then easily convert them to event listeners later if we find that we actually need to handle event bubbling and so forth.

There are three steps involved in moving event handlers out of the HTML into the Javascript.

The first step is to rewrite the HTML to remove the event handler (don't forget to take a copy of the event handler code first). In order to be able to attach the event handler to the specific HTML tag we will need to add an id to the tag if it doesn't already have one.

<a href="page1.htm" id="page2">

The second step is to write the Javascript code to link the event handler processing to the HTML.

document.getElementById('page2').onclick = function() {location.href='page2.htm';return false;}

The third and final step is to insert this code into our Javascript in such a way as to make sure that it doesn't try to run before the HTML tag has actually loaded into the browser (other wise we'll get an object not found error). We could do this simply by placing this code into a function attached to the window.onload event handler but this will mean that our event handler will not actually function until after the page finishes loading. That means that our page appears to work differently because we moved the event handler. If we instead use a script that tests for when a specific id has loaded so as to attach the event as soon as possible then our page will appeat to function exactly the same way as before we moved the event handler out of the HTML.

©2016 About.com. All rights reserved.