Understanding The JavaScript Event Model (part 2) - X Marks The Spot (Page 4 of 10 )
The "layerX" and "layerY" properties return the horizontal and vertical position, in pixels, of the cursor relative to the layer it is in.
The following example demonstrates:
<html>
<head>
<script language="JavaScript">
document.onmousedown = CoordCheck;
function CoordCheck(e)
{
if((e.x < 10 || e.y < 10) || e.x > 420 || e.y > 60)
{
alert ("OUTSIDE!!");
}
else
{
alert("INSIDE!!")
}
}
</script>
</head>
<body>
<layer id="tryme" left="10" top="10" width="410" height="50"
bgcolor="cyan"> Try clicking the mouse outside this layer. Then try
clicking inside. </layer>
</body>
</html>
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.
Next: Enter The Stalker >>
More JavaScript Articles
More By Team Melonfire, (c) Melonfire