1. Home
  2. Computing & Technology
  3. JavaScript

Moving JavaScript out of the Web Page

Moving Event Handlers

Related Articles

Moving Script Content

One of the most useful ways that JavaScript can be used to add functionality to a web page is to perform some sort of processing in response to an action by your visitor. The most common action that you want to respond to will be when that visitor clicks on something. The event handler that allows you to respond to visitors clicking on something is called onclick.

When most people first think about adding an onclick event handler to their web page they immediately think of adding it to an <a> tag. This gives a piece of code that often looks like:

<a href="#" onclick="dosomething(); return false;">

This is the wrong way to use onclick unless you have an actual meaningful address in the href attribute so that those without JavaScript will be transferred somewhere when they click on the link. A lot of people also leave out the "return false" from this code and then wonder why the top of the current page always gets loaded after the script has run (which is what the href="#" is telling the page to do unless false is returned from all the event handlers. Of course if you have something meaningful as the destination of the link then you may want to go there after running the onclick code and then you will not need the "return false".

What many people do not realise is that the onclick event handler can be added to any HTML tag in the web page in order to interact when your visitor clicks on that content. So if you want something to run when people click on an image you can use:

<img src="myimg.gif" onclick="dosomething()">

If you want to run something when people click on some text you can use:

<span onclick="dosomething()">some text</span>

Of course these don't give the automatic visual clue that there will be a response if your visitor clicks on them the way that a link does but you can add that visual clue easily enough yourself by styling the image or span appropriately.

The other thing to note about these ways of attaching the onclick event handler is that they do not require the "return false" because there is no default action that will happen when the element is clicked on that needs to be disabled.

These ways of attaching the onclick are a big improvement on the poor method that many people use but it is still a long way from being the best way of coding it. One problem with adding onclick using any of the above methods is that it is still mixing your JavaScript in with your HTML. onclick is not an HTML attribute, it is a JavaScript event handler. As such to separate our JavaScript from our HTML to make the page easier to maintain we need to get that onclick reference out of the HTML file into a separate JavaScript file where it belongs.

The easiest way to do this is to replace the onclick in the HTML with an id that will make it easy to attach the event handler to the appropriate spot in the HTML. So our HTML might now contain one of these statements:

< img src="myimg.gif" id="img1">
<span id="sp1">some text</span>

We can then code the JavaScript in a separate JavaScript file that is either linked into the bottom of the body of the page or which is in the head of the page and where our code is inside a function that is itself called after the page finishes loading. Our JavaScript to attach the event handlers now looks like this:

document.getElementById('img1').onclick = dosomething;
document.getElementById('sp1').onclick = dosomething;

One thing to note. You will notice that I have always written onclick entirely in lowercase. When coding the statement in their HTML you will see some people write it as onClick. This is wrong as the JavaScript event handlers names are all lowercase and there is no such handler as onClick. You can get away with it when you include the JavaScript inside your HTML tag directly since HTML is not case sensitive and the browser will map it across to the correct name for you. You can't get away with wrong capitalisation in your JavaScript itself since the JavaScript is case sensitive and there is no such thing in JavaScript as onClick.

This code is a huge improvement over the prior versions because we are now both attaching the event to the correct element within our HTML and we have the JavaScript completely separate from the HTML. We can improve on this even further though.

The one problem that is remaining is that we can only attach one onclick event handler to a specific element. Should we at any time need to attach a different onclick event handler to the same element then the previously attached processing will no longer be attached to that element. When you are adding a variety of different scripts to your web page for different purposes there is at least a possibility that two or more of them may want to provide some processing to be performed when the same element is clicked on. The messy solution to this problem is to identify where this situation arises and to combine the processing that needs to be called together into a function that performs all of the processing.

While clashes like this are less common with onclick than they are with onload, having to identify the clashes in advance and combine them together is not the ideal solution. It is not a solution at all when the actual processing that needs to be attached to the element changes over time so that sometimes there is one thing to do, sometimes another, and sometimes both.

The best solution is to stop using an event handler completely and to instead use a JavaScript event listener (along with the corresponding attachEvent for Jscript- since this is one of those situations where JavaScript and Jscript differ). We can do this most easily by first creating an addEvent function that will add either an event listener or attachevent depending on which of the two that the language being run supports;

function addEvent(el, eType, fn, uC) {
if (el.addEventListener) {
el.addEventListener(eType, fn, uC);
return true;
} else if (el.attachEvent) {
return el.attachEvent('on' + eType, fn);
}
}

We can now attach the processing that we want to have happen when our element is clicked on using:

addEvent(
document.getElementById('spn1'),
'click',dosomething,false);

Using this method of attaching the code to be processed when an element is clicked on means that making another addEvent call to add another function to be run when a specific element is clicked on will not replace the prior processing with the new processing but will instead allow both of the functions to be run. We have no need to know when calling an addEvent whether or not we already have a function attached to the element to run when it is clicked on, the new function will be run along with and functions that were previously attached.

Should we need the ability to remove functions from what gets run when an element is clicked on then we could create a corresponding deleteEvent function that calls the appropriate function for removing an event listener or attached event.

The one disadvantage of this last way of attaching the processing is that really old browsers do not support these relatively new ways of attaching event processing to a web page. There should be few enough people using such antiquated browsers by now to disregard them in what J(ava)Script we write apart from writing our code in such a way that it doesn't cause huge numbers of error messages. The above function is written so as to do nothing if neither of the ways it uses is supported. Most of these really old browsers do not support the getElementById method of referencing HTML either and so a simple if (!document.getElementById) return false; at the top of any of your functions which do such calls would also be appropriate. Of course many people writing JavaScript are not so considerate of those still using antique browsers and so those users must be getting used to seeing JavaScript errors on almost every web page they visit by now.

Which of these different ways do you use to attach processing into your page to be run when your visitors click on something? If the way you do it is nearer to the examples at the top of the page than to those examples at the bottom of the page then perhaps it is time you thought about improving the way you write your onclick processing to use one of the better methods presented lower down on the page.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.