Learn all about events in JavaScript, and how you can use them for all sorts of neat tricks.
Events allow you to write JavaScript code that reacts to certain situations. Examples of events include:
To allow you to run your bits of code when these events occur, JavaScript provides us withevent 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 theTAB 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. |
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"
, whereSomeJavaScriptCode
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.
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
onDragDrop
event. Returns an array of URLs of dropped objects.
Event.height
Event.modifiers
ALT_MASK
,
CONTROL_MASK
,
SHIFT_MASK
and
META_MASK
.
Event.pageX
Event.pageY
Event.screenX
Event.screenY
Event.target
Event.type
Event.which
Event.width
Event.x
Event.y
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.)
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).
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>
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.
In this example, an alert box is displayed when you click on the link below.
<a href="#" onclick="alert('Thanks!')">Click Me!</a>
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.
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.
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. Ifevent.which
is undefined it uses event.keyCode
instead (Internet Explorer usesevent.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>
onLoad
The onLoad
event handler is triggered when the page has finished loading. Common uses ofonLoad
include the dreaded pop-up advertisement windows, and to start other actions such as animations or timers once the whole page has finished loading.
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>
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.
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>
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.
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>