Main Page

Mouse events

Mouse events
Mouse events are the most commonly used group of events on the Web. They include the following:
?
click
— Occurs when the user clicks the left mouse button (not if the right mouse button is
used). Also occurs when focus is on a button and the user presses the Enter key.
?
dblclick
— Occurs when the user double clicks the left mouse button (not if the right mouse
button is used).
?
mousedown
— Occurs when the user pushes any mouse button down.
?
mouseout
— Occurs when the cursor is over an element and the user moves it outside the
boundaries of the element.
?
mouseover
— Occurs when the cursor is outside of an element and the user moves it over the
element.
?
mouseup
— Occurs when the user releases any mouse button.
?
mousemove
— Occurs repeatedly when the cursor is over an element.
All elements on a page support the mouse events. This simple example illustrates all the mouse events:
<html>
<head>
<title>Mouse Events Example</title>
<script type=”text/javascript”>
function handleEvent(oEvent) {
var oTextbox = document.getElementById(“txt1”);
oTextbox.value += “\n” + oEvent.type;
}
</script>
</head>
<body>
<p>Use your mouse to click and double click the red square.</p>
<div style=”width: 100px; height: 100px; background-color: red”
onmouseover=”handleEvent(event)”
onmouseout=”handleEvent(event)”
onmousedown=”handleEvent(event)”
onmouseup=”handleEvent(event)”
onclick=”handleEvent(event)”
ondblclick=”handleEvent(event)” id=”div1”></div>
<p><textarea id=”txt1” rows=”15” cols=”50”></textarea></p>
</body>
</html>
This code displays a red square and a text box. When you interact with the red square using your mouse,
the text box displays the events that are fired. Note that just one function is used as an event handler for
all events. It simply outputs the type of event into the text box.
280
Chapter 9
12_579088 ch09.qxd 3/28/05 11:39 AM Page 280


JavaScript EditorFree JavaScript Editor     Ajax Editor


©