Client-Side Scripting with JavaScript


Part 5 - Event Handlers and Objects

Event Handlers

Event handlers can trigger a JavaScript commands based on an event. These are often placed in anchor or form tags.

Selected Events

onMouseOver Pointer moves over an item
onMouseOut Pointer moves off an item
onLoad A page finishes loading
onUnload Exiting the document
onClick A link or form item is clicked
onFocus An item gains focus
onBlur An item loses focus

Examples

Changing the status line when pointing at a link:

<A HREF="http://www.ship.edu" onMouseOver="window.status='A Great Link!'; return true" onMouseOut="window.status='JavaScript Workshop'; return true"> Shippensburg University</A>

Point your mouse over this link and look at the status line at the bottom of the window.

This example use a function defined in a script, along with an event handler, to change the background color when the mouse passes over the link:

<SCRIPT LANGUAGE="JavaScript"> colors = new Array("White", "Blue", "Lime", "Aqua"); maxsub = colors.length; sub = 0; function changeBG() { sub++; if (sub >= maxsub) {sub=0} document.bgColor=colors[sub] } </SCRIPT> <A HREF="" onMouseOver="changeBG()"> Change colors </A>

Try pointing at this link to change background colors.

This page has the following event handler:

<BODY onUnload="window.alert('Goodbye! Come back soon.');"> Whenever you leave the page, you'll get an annoying alert box.

Objects

The examples given up to now have used a variety of objects within the browser environment. Objects have different properties and methods that you can access and set with JavaScript.

Top-level object: window
window.status - property (status line at bottom)
window.alert - method (displays message box)

Page content object: - document
document.bgColor - property

Some properties can be set dynamically, while others can not.

Next Next: Getting Input from Users