PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Eight Weeks of Prototype: Week 4, Event Handling in Prototype

Handling Mouse Events

It is possible to return the coordinates of the mouse for a particular event using the Event.pointerX() and Event.pointerY() functions. You simply pass in the event object passed to the event handler as the first and only argument to receive the integer value representing the location of the mouse.

These methods return values relative to the entire page, not just what is currently visible to you. In other words, if you've scrolled down on the page the returned values are still relative to the very top of the page.

Listing 13 shows an example of tracking the mouse movement within a particular element using the mousemove event. This event is triggered every time the mouse is moved whilst over this element. In the handler function we read the X and Y position of the mouse and update the element to display this information.

Listing 13 Reading the X and Y coordinates of the mouse (listing-13.html)
<html>
    <head>
        <title>Reading the X and Y coordinates of the mouse</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div id="foo">
            Move the mouse over me
        </div>
 
        <script type="text/javascript">
            function onMouseMove(e)
            {
                var element = Event.element(e);
                element.update(Event.pointerX(e) + 'x' + Event.pointerY(e));
            }
 
            $('foo').observe('mousemove', onMouseMove);
        </script>
    </body>
</html>

In This Article