Events and Event Handlers

Learn all about events in JavaScript, and how you can use them for all sorts of neat tricks.

What are events?

Events allow you to write JavaScript code that reacts to certain situations. Examples of events include:

  • The user clicking the mouse button
  • The Web page loading
  • A form field being changed

Event handlers

To allow you to run your bits of code when these events occur, JavaScript provides us with event handlers. All the event handlers in JavaScript start with the word on, and each event handler deals with a certain type of event. Here's a list of all the event handlers in JavaScript, along with the objects they apply to and the events that trigger them:

Event handler Applies to: Triggered when:
onAbort Image The loading of the image is cancelled.
onBlur Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window The object in question loses focus (e.g. by clicking outside it or pressing the TAB key).
onChange FileUpload, Select, Text, TextArea The data in the form element is changed by the user.
onClick Button, Document, Checkbox, Link, Radio, Reset, Submit The object is clicked on.
onDblClick Document, Link The object is double-clicked on.
onDragDrop Window An icon is dragged and dropped into the browser.
onError Image, Window A JavaScript error occurs.
onFocus Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window The object in question gains focus (e.g. by clicking on it or pressing the TAB key).
onKeyDown Document, Image, Link, TextArea The user presses a key.
onKeyPress Document, Image, Link, TextArea The user presses or holds down a key.
onKeyUp Document, Image, Link, TextArea The user releases a key.
onLoad Image, Window The whole page has finished loading.
onMouseDown Button, Document, Link The user presses a mouse button.
onMouseMove None The user moves the mouse.
onMouseOut Image, Link The user moves the mouse away from the object.
onMouseOver Image, Link The user moves the mouse over the object.
onMouseUp Button, Document, Link The user releases a mouse button.
onMove Window The user moves the browser window or frame.
onReset Form The user clicks the form's Reset button.
onResize Window The user resizes the browser window or frame.
onSelect Text, Textarea The user selects text within the field.
onSubmit Form The user clicks the form's Submit button.
onUnload Window The user leaves the page.

Using an event handler

To use an event handler, you usually place the event handler name within the HTML tag of the object you want to work with, followed by ="SomeJavaScriptCode", where SomeJavaScriptCode is the JavaScript you would like to execute when the event occurs.

For example:


<input type="submit" name="clickme"
value="Click Me!" onclick="alert('Thank You!')"/>

Although the original JavaScript event handler name contains capital letters ("onClick"), you should use all lowercase in the HTML itself ("onclick") if you want your markup to follow the XHTML specification (which we do!). All element names and attributes must be lowercase in XHTML.

The Event object

The Event object is created automatically whenever an event occurs. There are a number of properties associated with the Event object that can be queried to provide additional information about the event:

Event.data
Used by the onDragDrop event. Returns an array of URLs of dropped objects.
Event.height
Stores the height of the window or frame containing the object connected with the event.
Event.modifiers
Returns a string listing any modifier keys that were held down during a key or mouse event. The modifier key values are: ALT_MASK, CONTROL_MASK, SHIFT_MASK and META_MASK.
Event.pageX
Event.pageY
These properties hold the X and Y pixel coordinates of the cursor relative to the page, at the time of the event.
Event.screenX
Event.screenY
These properties hold the X and Y pixel coordinates of the cursor relative to the screen, at the time of the event.
Event.target
Returns a string representing the object that initiated the event.
Event.type
Returns a string representing the type of the event (keypress, click, etc).
Event.which
Returns a number representing the mouse button that was pressed (1=left, 2=middle, 3=right) or the ASCII code of the key that was pressed.
Event.width
Stores the width of the window or frame containing the object connected with the event.
Event.x
Event.y
These properties hold the X and Y pixel coordinates of the cursor relative to the layer connected with the event or, for the onResize event, the width and height of the object after it was resized. (You can also use event.layerX and event.layerY, which do the same thing.)

Some common event handlers

In this section, we'll look at a few of the more commonly used event handlers, and examine how they can be used.

onChange

onChange is commonly used to validate form fields (see our tutorial on Form validation with JavaScript) or to otherwise perform an action when a form field's value has been altered by the user. The event handler is triggered when the user changes the field then clicks outside the field or uses the TAB key (i.e. the object loses focus).

Example

This example code ensures that you type in both your first and your last names. It will bring up an alert box and refocus the text box field if you only type one word into the text box.


Please enter your name: <input type="text"
name="your_name" onchange="validateField(this)"/>

<script type="text/javascript">

function validateField ( fieldname )
{
    if ( ( fieldname.value ) &&
    ( ! fieldname.value.match ( " " ) ) )
    {
        alert ( "Please enter your first and last names!" );
        fieldname.focus ( );
    }
}

</script>

Please enter your name:

onClick

The onClick handler is executed when the user clicks with the mouse on the object in question. Because you can use it on many types of objects, from buttons through to checkboxes through to links, it's a great way to create interactive Web pages based on JavaScript.

Example

In this example, an alert box is displayed when you click on the link below.


<a href="#" onclick="alert('Thanks!')">Click Me!</a>

Click Me!

onFocus

onFocus is executed whenever the specified object gains focus. This usually happens when the user clicks on the object with the mouse button, or moves to the object using the TAB key. onFocus can be used on most form elements.

Example

This example text box contains the prompt "Please enter your email address" that is cleared once the text box has focus.


<input type="text" name="email_address"
size="40" value="Please enter your email address"
onfocus="this.value=''"/>

onKeyPress

You can use onKeyPress to determine when a key on the keyboard has been pressed. This is useful for allowing keyboard shortcuts in your forms and for providing interactivity and games.

Example

This example uses the onKeyPress event handler for the Window object to determine when a key was pressed. In addition, it uses the which property of the Event object to determine the ASCII code of the key that was pressed, and then displays the pressed key in a text box. If event.which is undefined it uses event.keyCode instead (Internet Explorer uses event.keyCode instead of event.which).


<html>

<body onkeypress = "show_key(event.which)">

<form method="post" name="my_form">

The key you pressed was:
<input type="text" name="key_display" size="2"/>

</form>

<script type="text/javascript">

function show_key ( the_key )
{
    if ( ! the_key )
    {
        the_key = event.keyCode;
    }

    document.my_form.key_display.value
    = String.fromCharCode ( the_key );
}

</script>

</body>

</html>

Try it out!

onLoad

The onLoad event handler is triggered when the page has finished loading. Common uses of onLoad include the dreaded pop-up advertisement windows, and to start other actions such as animations or timers once the whole page has finished loading.

Example

This simple example displays an alert box when the page has finished loading:


<html>
<body onload = "alert('Thanks for visiting my page!')">

My Page

</body>
</html>

Try it out!

onMouseOut, onMouseOver

The classic use of these two event handlers is for JavaScript rollover images (images, such as buttons, that change when you move your mouse over them). We have a tutorial on just this topic called Rollover buttons with JavaScript.

Example

Here's a simple example that alters the value of a text box depending on whether the mouse pointer is over a link or not.


<form>

<input type="text" id="status" value="Not over the link"/>

<br>

<a href="" onmouseover="document.getElementById('status').value='Over the link'"
onmouseout="document.getElementById('status').value='Not over the link'">Move
the mouse over me!</a>

</form>


Move the mouse over me!

onSubmit

The onSubmit event handler, which works only with the Form object, is commonly used to validate the form before it's sent to the server. In fact we have a whole tutorial on this topic, called Form validation with JavaScript.

Example

This example asks you to confirm whether you want to submit the form or not when you click on the button. It returns true to the event handler if the form is to be submiited, and false if the submission is to be cancelled.


<form onsubmit="return confirm('Are You Sure?')" action="">

<input type="submit" name="submit" value="Submit"/>

</form>

Follow Elated

Related articles

Responses to this article

3 responses (oldest first):

17-Dec-09 15:00
would the mouseover and mouseout effects be the best way to produce a "fisheye" effect. For instance replacing an image with a larger one on mouseover?
17-Dec-09 19:51
Probably, yes. Here's a tutorial on JavaScript rollovers that might help:

http://www.elated.com/articles/rollover-buttons-with-javascript/

You'll probably want to increase the width and height of the image in the onmouseover handler, and decrease them again in the onmouseout handler.

Cheers,
Matt
05-Feb-12 11:20
Replacement for alert event

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page