HomeJavaScript Page 5 - Understanding The JavaScript Event Model (part 2)
Enter The Stalker - 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.
Here's another example, this one demonstrating how the current coordinates of the mouse pointer can be exploited to create a simple mouse trail. Take a look at the following example, which has a text string closely following the mouse pointer as it travels across the screen.
<html>
<head>
<script language="JavaScript">
function mouseTracker()
{
document.all.rock_n_roll.style.visibility="visible";
document.all.rock_n_roll.style.left = event.x + 20;
document.all.rock_n_roll.style.top = event.y + 20;
}
document.onmousemove=mouseTracker;
</script>
</head>
<body>
<div id="rock_n_roll" style="font-family:Arial; font-size: xx-small;
position:absolute; visibility:hidden; background:black; color:
white;">Why are you following me?</div>
</body>
</html>
In this case, every time the mouse is moved, an event is generated and the mouseTracker() function is invoked. This function receives the current X and Y coordinates of the mouse pointer; it then uses these coordinates to move the layer containing the text string to a location 20 pixels behind the pointer.
Here's the Netscape version of the example above - as you can see, it does exactly the same thing, except that it uses the "pageX" and "pageY" properties instead of the "x" and "y" properties.
<html>
<head>
<script language="JavaScript">
function mouseTracker(e)
{
document.rockroll.visibility="show"
document.rockroll.pageX = e.pageX + 20
document.rockroll.pageY = e.pageY + 20
}
document.captureEvents(Event.MOUSEMOVE);
document.onMouseMove=mouseTracker;
</script>
</head>
<body>
<div id="rockroll" style="position:absolute; visibility:hidden;
background:black; color:white;"><font face="Arial" size="-2">Why are you
following me?</font></div>
</body>
</html>