Home Page -> DOM Tutorials -> Using Events -> Setting Events

Setting Events

In the CSS2 Document Object Model, you tell objects to listen to an event. Thus, we'll tell each <div> to listen for mouse click, mouse over, and mouse out events.

To make it easier to set the event listeners, we'll need a utility routine that gives us back a reference to an object in a document when we give the object's name. This function uses variable isNav6, which is part of the domUtils.js package introduced in an earlier tutorial.

function getObject( objName )
{
    if (isNav6)
    {
        return document.getElementById( objName );
    }
}

Once we have the object, we can add an event listener with a statement of this form:

obj.addEventListener( "name", functionName, useCapture );

where:

name
is the name of the event you want the object to listen for
functionName
is the name of the function that will process that event
useCapture
is a boolean that tells whether you want to use event capturing (true) or event bubbling (false).
[Don't know what those mean? See the details here.]

So, what looks like this in HTML:

<div id="m0"
  onMouseOver="highlight()">

Is achieved like this when using the DOM:

var obj = getObject("m0");
obj.addEventListener( "mouseover", highlight, false );

We use the getObject function from above to write a setup() function to add the event listeners to each of the menu <div>s, which have ids of m0, m1, and m2.

var nMenus = 3;

function setup( )
{
    var i;
    var obj;

    for (i=0; i < nMenus; i++)
    {
        obj = getObject( "m" + n );
        if (isNav6)
        {
            obj.addEventListener( "mouseover", highlight, false );
            obj.addEventListener( "mouseout", dim, false );
            obj.addEventListener( "click", showMenu, false );
        }
    }
}

Now, we have to write the highlight(), dim(), and showMenu() functions. In order to do this, we must first understand the concept of a Node.

  New Menu Example  Index About Nodes