Events and Event Handlers in JavaScript

Web programming topics
Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

Events and Event Handlers in JavaScript

Post by Neo » Mon Mar 01, 2010 10:57 am

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 handlerApplies to:Triggered when:
onAbortImageThe loading of the image is cancelled.
onBlurButton, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, WindowThe object in question loses focus (e.g. by clicking outside it or pressing the TAB key).
onChangeFileUpload, Select, Text, TextAreaThe data in the form element is changed by the user.
onClickButton, Document, Checkbox, Link, Radio, Reset, SubmitThe object is clicked on.
onDblClickDocument, LinkThe object is double-clicked on.
onDragDropWindowAn icon is dragged and dropped into the browser.
onErrorImage, WindowA JavaScript error occurs.
onFocusButton, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, WindowThe object in question gains focus (e.g. by clicking on it or pressing the TAB key).
onKeyDownDocument, Image, Link, TextAreaThe user presses a key.
onKeyPressDocument, Image, Link, TextAreaThe user presses or holds down a key.
onKeyUpDocument, Image, Link, TextAreaThe user releases a key.
onLoadImage, WindowThe whole page has finished loading.
onMouseDownButton, Document, LinkThe user presses a mouse button.
onMouseMoveNoneThe user moves the mouse.
onMouseOutImage, LinkThe user moves the mouse away from the object.
onMouseOverImage, LinkThe user moves the mouse over the object.
onMouseUpButton, Document, LinkThe user releases a mouse button.
onMoveWindowThe user moves the browser window or frame.
onResetFormThe user clicks the form's Reset button.
onResizeWindowThe user resizes the browser window or frame.
onSelectText, TextareaThe user selects text within the field.
onSubmitFormThe user clicks the form's Submit button.
onUnloadWindowThe 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:

Code: Select all

<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.dataUsed by the onDragDrop event. Returns an array of URLs of dropped objects
Event.heightStores the height of the window or frame containing the object connected with the event
Event.modifiersReturns 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.pageYThese properties hold the X and Y pixel coordinates of the cursor relative to the page, at the time of the event
Event.screenX Event.screenYThese properties hold the X and Y pixel coordinates of the cursor relative to the screen, at the time of the event
Event.targetReturns a string representing the object that initiated the event
Event.typeReturns a string representing the type of the event (keypress, click, etc)
Event.whichReturns 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.widthStores the width of the window or frame containing the object connected with the event
Event.x Event.yThese 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.

Code: Select all

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.

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

Code: Select all

<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.

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

Code: Select all

<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).

Code: Select all

<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 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:

Code: Select all

<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.

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.

Code: Select all

<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.

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 submitted, and false if the submission is to be cancelled.

Code: Select all

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

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

</form> 
Post Reply

Return to “Web programming”