Path // www.yourhtmlsource.comJavaScript → EVENTS HANDLERS

Event Handlers


Now we're going to get onto the dynamic parts of JavaScript. Events are occurrences triggered by a user interacting with your page, whether it be clicking on something or just moving their mouse around. By the end of this tutorial you'll have things responding to all sorts of user interactions.

Clock This page was last updated on 2012-08-21



Basic Events

When a user triggers an event, your browser usually does something in response. Click a link, and it loads up the page in the link's href. Click into a form field and it receives the browser's focus. These are the default event handlers for each object in a HTML page. When we write our own event handlers, we write them directly into the HTML code so the browser knows which element we're addressing, and add in new commands on top of the existing default actions. Event Handlers aren't scripts in themselves, but often use variables, methods and functions from scripts to perform their action.

There are a myriad of standard and proprietary events that can occur on your page, but we'll start with some of the most common — mouseOver, Load and Click.

Browser Compatibility Note:

Events have been around since JavaScript began — back in Netscape 2. The basic events are supported by all browsers, but the more recently added ones have patchier support. Netscape 4 is the most unreliable browser in circulation. IE5+, » Firefox and Opera 6 are all pretty good.

Assigning Handlers

First we need to add the event handler to the object it's going to work with. This comes in the form of an attribute for the HTML tag. We'll add it to a link. The code is:

<a href="http://www.yourhtmlsource.com" onMouseOver="window.status='Go back to the Homepage';
return true">Home</a>

Which will create Home. Have a look at your browser's status bar (at the bottom) as you hover on the link. The handler waits until the event it is designed to react to occurs, or 'fires', and then gets busy when you place your mouse on the link by changing to the text we've given in the command. (Firefox users should note that by default, Firefox doesn’t allow JavaScript to change the contents of the status bar, so you won’t see the effect. You can change this in Firefox’s Options panel.)

So what have we done here, exactly? Firstly, onMouseOver is just an attribute like any other, except it takes JavaScript code as its value. In this case we're taking the window object (which holds everything else on the page inside it, including document), and using its status property, changing it to the string 'Go back to the Homepage'. Remember, objects and methods/properties are separated by a dot. Note the single quotes around the text too. After this comes a semicolon, meaning we've finished a command.

sourcetip: The style of capitalisation for the event handlers that I’m using in these tutorials (i.e., onMouseOver) is just a tradition. Writing them any other way won't change how they work. Remember that if you're using XHTML your event handler attribute names will have to be all in lowercase, so you'll use onmouseover.

The return true command at the end means that the default action should also occur (if the user clicks, the link is followed). It is a boolean value, meaning it can take two values — true or false. Setting this to false will stop the default action from occurring. So, for example, you can disable a link by setting its click event to return false.

Writing text into the status bar is an exception to the return rule. You'd think that you'd set it to false to stop the default action of displaying the href from occuring, but this isn't the case. It must return true for the handler to perform.

If you use this handler on your own page you'll probably find that once the status bar has been set to something it stays like that. That's not so good, so we want to set some default text that will retain its place in the bar after your mouse has left the link. Luckily, the window has a property defaultStatus that we can assign a value to.

We'll do this using the onLoad event, which is triggered when the page loads fully. Change your <body> tag to this:

<body onLoad="window.defaultStatus='Welcome to my site'">

You should be getting familiar with the notation we're using now. Once again, we're using a property of window, and assigning a string to it. I have a default status on every page in HTML Source, and as you can see with the example above, the status bar returns to this text after every mouseOver.

sourcetip: Unlike HTML, the capitalisation of JavaScript properties and methods is important to get right. defaultStatus must be typed exactly as you see it here if it is to work.

This loading event will become very useful later on, when we only want our script to become active once the entire page, and its images and arrays are loaded. There are loads of properties for window and every other object, but we'll get into them later, on more specific pages.

One more basic event handler is onClick. We'll set up a button that triggers an alert when it's clicked. The code shall be

<button onClick="alert('Boo!'); return false;">Click me</button>

Which will create

Pretty simple, eh? The alert object is actually underneath window in the object hierarchy, but window can usually be left out since all other objects are held inside it. In this case, window.alert could be used, but there's no need to specifically reference the window unless you have opened more than one. By the same token, you could re-code the examples above with simply status='', if you prefer.

The window also fires an event when it starts to unLoad, which happens when a link is followed, or when the window is closed. You can't distinguish between the two causes of this event, and you cannot stop the page from being closed. This is most useful for opening more windows when the user leaves your site.

Form Events

The following events usually occur when a user is interacting with a form. They are onFocus, onBlur, onChange and onSelect.

OnFocus takes effect when an object receives the browser's focus — that is, if the user is currently doing something with that object. If you click on a form field, it receives the focus. Try it below:

Here I'm giving an example of blur too. When an element loses the focus, it is said to be blurred. So onBlur kicks into action when you click away from the object after it has had the focus. Don't worry about how I'm actually changing the text in the box, we'll be getting onto that very soon.

OnChange takes effect when the value of a text box or area is changed from its initial value. Modify this:

Once you move away from the input box, the change is registered. The code to create the text box is:

<input type="text" value="Change me" onchange="alert('You\'ve changed, man');">

Note that in the alert text, I used an apostrophe. Since you can't do that normally, as it ends the string early, I escaped the character with a backslash. This is a common occurrence in programming. The backslash won't turn up in the alert, it just allows you to use the apostrophe.

One more event comes into play when some text is selected in a field. We'll get into more specific examples of when onSelect is useful a couple of tutorials down the line.

All forms also have the submit and reset events — you can guess when they're fired. These come in very useful when we got onto form validation — using onSubmit you can check if the form is filled in properly before sending the data.

Modern Events

In most modern browsers you can assign event handlers to any HTML element (in the beginning it was just links and forms). A number of all-new events were added to browser's abilities to increase the level of interaction you can achieve.

Along with the traditional trio of click, mouseOver and mouseOut we now have dblClick; and you can control the click event to a much sharper degree using mouseDown and mouseUp, corresponding to the mouse button being clicked and then being released. You can also react to a mouseMove. I'm sure you know how to create handlers for all these events — the naming convention is simply to add 'on' to the event name.

In the version 4 browsers events were added to relate to actions with the keyboard. KeyDown and keyUp fire when you'd expect. If a key is held down, keyPress fires continuously. You are able to find out which key is being pressed — we'll get onto that in time.