Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Using Mouse Events

The DOM includes a number of event handlers for detecting mouse actions. Your script can detect the movement of the mouse pointer and when a button is clicked, released, or both.

Over and Out

You've already seen the first and most common event handler, onMouseOver. This handler is called when the mouse pointer moves over a link or other object.

The onMouseOut handler is the oppositeit is called when the mouse pointer moves out of the object's border. Unless something strange happens, this always happens sometime after the onMouseOver event is called.

This handler is particularly useful if your script has made a change when the pointer moved over the objectfor example, displaying a message in the status line or changing an image. You can use an onMouseOut handler to undo the action when the pointer moves away.

You'll use both onMouseOver and onMouseOut handlers in the "Try it Yourself: Adding Link Descriptions to a Web Page" section at the end of this hour.

By the Way

One of the most common uses for the onMouseOver and onMouseOut event handlers is to create rolloversimages that change when the mouse moves over them. You'll learn how to create these in Hour 19, "Using Graphics and Animation."


Using the onMouseMove Event

The onMouseMove event occurs any time the mouse pointer moves. As you might imagine, this happens quite oftenthe event can trigger hundreds of times as the mouse pointer moves across a page.

Because of the large number of generated events, browsers don't support the onMouseMove event by default. To enable it for a page, you need to use event capturing. This is similar to the dynamic events technique you learned earlier in this hour, but requires an extra step for some older browsers.

The basic syntax to support this event, for both browsers, is to set a function as the onMouseMove handler for the document or another object. For example, this statement sets the onMouseMove handler for the document to a function called MoveHere, which must be defined in the same page:

document.onMouseMove=MoveHere;

Additionally, older versions of Netscape require that you specifically enable the event using the document.captureEvents method:

document.captureEvents(Event.MOUSEMOVE);

Ups and Downs (and Clicks)

You can also use events to detect when the mouse button is clicked. The basic event handler for this is onClick. This event handler is called when the mouse button is clicked while positioned over the appropriate object.

By the Way

The object in this case can be a link. It can also be a form element. You'll learn more about forms in Hour 11, "Getting Data with Forms."


For example, you can use the following event handler to display an alert when a link is clicked:

<a href="http://www.jsworkshop.com/"
onClick="alert('You are about to leave this site.');">Click Here</a>

In this case, the onClick event handler runs before the linked page is loaded into the browser. This is useful for making links conditional or displaying a disclaimer before launching the linked page.

If your onClick event handler returns the false value, the link will not be followed. For example, the following is a link that displays a confirmation dialog. If you click Cancel, the link is not followed; if you click OK, the new page is loaded:

<a href="http://www.jsworkshop.com/"
onClick="return(window.confirm('Are you sure?"));">
Click Here</a>

This example uses the return statement to enclose the event handler. This ensures that the false value that is returned when the user clicks Cancel is returned from the event handler, which prevents the link from being followed.

The onDblClick event handler is similar, but is only used if the user double-clicks on an object. Because links usually require only a single click, you could use this to make a link do two different things depending on the number of clicks. (Needless to say, this could be confusing.) You can also detect double-clicks on images and other objects.

To give you even more control of what happens when the mouse button is pressed, two more events are included:

  • onMouseDown is used when the user presses the mouse button.

  • onMouseUp is used when the user releases the mouse button.

These two events are the two halves of a mouse click. If you want to detect an entire click, use onClick. Use onMouseUp and onMouseDown to detect just one or the other.

To detect which mouse button is pressed, you can use the button property of the event object. This property is assigned the value 0 or 1 for the left button, and 2 for the right button. This property is assigned for onClick, onDblClick, onMouseUp, and onMouseDown events.

Watch Out!

Browsers don't normally detect onClick or onDblClick events for the right mouse button. If you want to detect the right button, onMouseDown is the most reliable way.


As an example of these event handlers, you can create a script that displays information about mouse button events and determines which button is pressed. Listing 9.1 shows the mouse event script.

Listing 9.1. The JavaScript file for the mouse click example.

function mousestatus(e) {
    if (!e) e = window.event;
    btn = e.button;
    whichone = (btn < 2) ? "Left" : "Right";
    message=e.type + " : "+ whichone + "\n";
    document.form1.info.value += message;
}
obj=document.getElementById("testlink");
obj.onmousedown = mousestatus;
obj.onmouseup = mousestatus;
obj.onclick = mousestatus;
obj.ondblclick = mousestatus;

This script includes a function, mousestatus(), that detects mouse events. This function uses the button property of the event object to determine which button was pressed. It also uses the type property to display the type of event, since the function will be used to handle multiple event types.

After the function, the script finds the object for a link with the id attribute testlink and assigns its onmousedown, onmouseup, onclick, and ondblclick events to the mousestatus function.

Save this script as click.js. Next, you will need an HTML document to work with the script, shown in Listing 9.2.

Listing 9.2. The HTML file for the mouse click example.

<html>
<head>
<title>Mouse click test</title>
</head>
<body>
<h1>Mouse Click Test</h1>
<p>Click the mouse on the test link below. A message below
will indicate which button was clicked.</p>
<h2><a href="#" id="testlink">Test Link</a></h2>
<form name="form1">
<textarea rows="10" cols="70" name="info"></textarea>
</form>
<script language="javascript" type="text/javascript"
   src="click.js">
</script>
</body>
</html>

This file defines a test link with the id property testlink, which is used in the script to assign event handlers. It also defines a form and a textarea used by the script to display the events. To test this document, save it in the same folder as the JavaScript file you created previously and load the HTML document into a browser. The results are shown in Figure 9.1.

Figure 9.1. The mouse click example in action.


By the Way

Notice that a single click of the left mouse button triggers three events: onMouseDown, onMouseUp, and then onClick.


Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Hour 9. Responding to Events
Understanding Event Handlers
Using Mouse Events
Using Keyboard Events
Using the onLoad and onUnload Events
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 10. Using Windows and Frames
Hour 11. Getting Data with Forms
Hour 12. Working with Style Sheets
Hour 13. Using the W3C DOM
Hour 14. Using Advanced DOM Features
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele