HTML and CSS Reference
In-Depth Information
EXAMPLE
13.23
<html>
<head><title>Mouse Coordinates</title>
<script type="text/javascript">
function getCoords(e) {
1
var x = 0; // x and y positions
var y = 0;
2
if (!e) var e = window.event; //
Internet Explorer
3
if (e.pageX || e.pageY){
//
Firefox
x = e.pageX
;
y = e.pageY
;
}
4
else if (e
.clientX || e.clientY
){
5
x =
e.clientX
+ document.body.scrollLeft
+ document.documentElement.scrollLeft;
y=
e.clientY
+ document.body.scrollTop
+ document.documentElement.scrollTop;
}
//
x and y contain the mouse position
//
relative to the document
alert(x +", "+ y);
}
</script>
<head>
<body>
<div style="background-color:aqua;position:absolute;top:50px"
onMouseover="return getCoords(event)
;">
<h1>Mouse positions are relative to the document, not the
<div> container</h1>
</div>
</body>
</html>
EXPLANATION
1
Variables
x
and
y
are declared. They will hold the pixel coordinates of the mouse.
2
If using Mozilla/Firefox, the value of
e
will be sent to the function; if using Inter-
net Explorer, the value of
window.event
will be assigned to
e
. In this way both
browsers will get a reference to the event triggered when the mouse event is fired.
3
The
pageX,pageY
pair represents the coordinates of a page regardless of scrollbars,
but this pair is not supported by Internet Explorer. See an excellent demo at
4
The
clientX,clientY
pair represents the coordinates of a page and accounts for
scrollbars.
5
The
clientX
and
clientY
pair return the position of the mouse pointer in the docu-
ment, whereas
offsetX
and
offsetY
return the position of the mouse pointer on the
element (see Figure 13.37).