HomeJavaScript Page 4 - Understanding The JavaScript Event Model (part 2)
X Marks The Spot - JavaScript
In this concluding article on the JavaScript event model, findout how the Event object can be used to do ever more complex things,including manipulating the dimensions of a Web page and tracking andintercepting keyboard and mouse events.
In this case, I have a layer of a specific height and width, and a function that detects when and where the mouse is clicked on the document. If the position of the pointer when the mouse is clicked is within the layer, an alert box shows up with an appropriate message; if the pointer is outside the layer, a different message appears.
The event object generated when the mouse button is clicked is passed to the JavaScript function CoordCheck(), which actually checks the position of the cursor and determines where it is in relation to the layer. I'll be going into the nitty-gritty of how JavaScript's mouse events work a little later; for the moment, concentrate on my use of the "layerX" and "layerY" properties in the example above.
Now, if you tried this example in Internet Explorer, you probably got hit with a couple of error messages. This is because Internet Explorer doesn't support "layerX" or "layerY", preferring instead to use the "x" and "y" properties. Take a look at this rewrite of the previous example, which demonstrates:
<html>
<head>
<script language="JavaScript">
document.onmousedown = CoordCheck;
function CoordCheck()
{
// uncomment the next two lines to see coordinate data
// alert ("The x-coordinate is " + event.x);
// alert ("The y-oordinate is " + event.y);
if((event.x < 10 || event.y < 10) || event.x > 420 || event.y >
60)
{
alert ("OUTSIDE!!");
}
else
{
alert("INSIDE!!")
}
}
</script>
</head>
<body>
<div style="background-color:cyan; position:absolute; top:10; left:10;
width:410; height:50"> Try clicking the mouse outside this layer. Then
try clicking inside. </div>
</body>
</html>
In addition to these properties, there's also the "screenX" and "screenY" properties, which return the horizontal and vertical position of the cursor relative to the screen. Netscape additionally exposes the "pageX" and "pageY" properties, which returns the horizontal and vertical position of the cursor relative to the page.