Home Page -> DOM Tutorials -> Using Events -> Finding the div

Finding the div

When an event occurs, the corresponding event listener function is invoked. This function should be written to expect one argument -- an Event object. Event objects have many useful properties; the one we're interested in is the target property, which tells us which Node is the event's intended target.

When we click the words or the image in a <div>, the target that gets returned is actually the text or the image inside the <div>, not the <div> itself. [The event's currentNode property is the one we really want, but it's not implemented in Mozilla release 15.]

Therefore, we have to write this function which checks to see if the target of the event we pass to it is a DIV element (tag). If not, the function keeps looking at that node's parentNode, and its parent, and so forth, until it finds a DIV element.

function findOwner( evt )
{
    var node = evt.target;
    while (node)
    {
        if ( node.nodeType == Node.ELEMENT_NODE &&
             node.nodeName == "DIV")
        {
            return node;
        }
        node = node.parentNode;
    }
    return null;
}

Once we have the <div>'s node, we can change its properties, which we'll need to do for the highlight() and dim() functions. Notice that we change the shape of the cursor when it moves over the <div>.

function highlight( evt )
{
    var obj = findOwner( evt );
    if (isNav6) { obj.style.cursor = "pointer"; }
    obj.style.color= "#ff0000"; // red
}

function dim( evt )
{
    var obj = findOwner( evt );
    if (isNav6) { obj.style.cursor = "default"; }
    obj.style.color = "#000000"; // black
}

  About Nodes  Index Implementing showMenu()