The following code is taken from the ‘JavaScript by Example Second Edition’.
I think the code
if (!e) var e = window.event; // Internet Explorer
should be
if (!e) e = window.event; // Internet Explorer
What do you think? Is it right? Or maybe the code should remains as is?
<html>
<head>
<title>Mouse Coordinates</title>
<script type="text/javascript">
function getCoords(e) {
var x = 0; // x and y positions
var y = 0;
if (!e) var e = window.event; // Internet Explorer
if (e.pageX || e.pageY) { // Firefox
x = e.pageX;
y = e.pageY;
}
else if (e.clientX || e.clientY) {
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>
Yes, you can remove the var statement inside that function.
Variables in functions are declared in scope in 2 ways, either via the ‘var’ keyword, or by being defined as a parameter being passed into the function.