O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Determining the Element the Cursor Rolled From/To

NN 6, IE 5

Problem

You want to know the element from which the cursor rolled into the current element or the element to which the user rolled the cursor.

Solution

The IE event model supplies two different property names—fromElement and toElement—to convey references to the relevant elements. In contrast, the W3C DOM event model lets one property—relatedTarget —handle both chores because the reference depends entirely upon which event is being processed. An mouseover event reveals the element from which the cursor came; an mouseout event reveals the element to which the cursor has gone. For example, the following element has mouse event handlers to invoke separate functions for cursor rolls into and out of the element:

<img src="myImg.jp" ... onmouseover="incoming(event)" onmouseout="outgoing(event") />

The following incoming( ) function applies event-property equalization to obtain a reference to the element from which the cursor rolled:

function incoming(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
        var from = (evt.relatedTarget) ? evt.relatedTarget : 
            ((evt.fromElement) ? evt.fromElement : null);
        if (from) {
            // work with adjacent "from" element
        }
    }
}

The parallel outgoing( ) function obtains a reference to the element to which the cursor has already rolled:

function outgoing(evt) { evt = (evt) ? evt : ((window.event) ? event : null); if (evt) { var to = (evt.relatedTarget) ? evt.relatedTarget : ((evt.toElement) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required