DOM Design Tips II – A Record Aside

On this tutorial, we’ll use the event-handling capabilities of the Doc Object Mannequin (DOM) to make some minor enhancements to the increasing thực đơn that we developed in a earlier tutorial. [Truth in advertising: these improvements are borderline cute; their real purpose is to serve as a vehicle to introduce the concepts of events and nodes.]Within the earlier tutorial, we mentioned utilizing the CSS show property to make an increasing thực đơn just like the one under. In that tutorial, solely the small plus or minus signal photos have been clickable. Nonetheless, should you strive the thực đơn under, you’ll see that each one the phrases in the primary headings are energetic and clickable; not simply the small plus or minus indicators. This gained’t work in Navigator 4.

Article Continues Beneath

plus sign Search Engines
plus sign Net Design
plus sign Digital Pictures

The unique code used the onMouseOver and onMouseOut occasion handlers to detect when the mouse moved over the pictures.Notice: the code that we’ll present within the textual content of this text is designed to work with Mozilla, a DOM-compliant browser. If you need code that can work on different browsers, you should utilize the cross-platform DOM utilities embody file, which was developed in one other article. Utilizing the View Web page Supply possibility in your browser will, after all, present the precise code.Earlier than we go into the code, although, now we have to debate the 2 ways in which the DOM handles occasions:

Capturing and Effervescent Occasions#section2

Other than utilizing onMouseOver and onMouseOut, the DOM enables you to connect an occasion listener to the objects in your doc. These listeners watch for occasions to happen, and they are often informed to hear for occasions in certainly one of two methods. The primary methodology is named occasion seize; the second known as occasion effervescent.

Occasion Seize#section3

diagram showing arrows moving downwardsLet’s say that your doc incorporates a <div> which incorporates a <p> which incorporates an <img>. Additional, let’s say you’ve added an occasion listener to all of them utilizing the seize methodology. When a consumer clicks on the picture, a mouseclick occasion happens.Regardless that the consumer clicked the picture, the picture doesn’t get the occasion first. As an alternative, the occasion listener connected to the doc grabs the occasion first and processes it. (That’s, it captures the occasion earlier than it will get to its meant goal.) The occasion is then handed all the way down to the <div>’s occasion listener. The occasion then goes to the <p>, and at last to the <img>. That’s, all the clicked-on object’s “ancestors” greater up within the doc seize the occasion for processing earlier than sending it down the chain to its meant goal. You’ll be able to strive occasion seize in a pop-up window. (This solely works in Mozilla.) [Ed. Note: Since this article was originally published, the event capture pop-up now works in most browsers.]

Occasion Effervescent#section4

diagram showing arrows moving upwardsNow let’s have a look at the identical scenario from the within out. You may have an <img> inside a <p>, which is inside a <div>, which is inside your doc. We’ve connected occasion listeners to all of the objects, specifying the bubble methodology. When a consumer clicks the picture, this time the occasions rise like a bubble in a glass of water. The clicking’s authentic goal, the <img>, will get to see the occasion first, after which passes it upwards to the <p> for additional processing, which passes it on to the <div>, which lastly passes it as much as the doc. You’ll be able to strive occasion effervescent in a pop-up window. (This solely works in Mozilla.) [Ed. Note: Refer to previous Editor’s Note.]Listed here are the related components of the supply code for each demos.

Setting Occasions#section5

Now that we all know how the DOM handles occasions, now we have to learn the way so as to add occasion listeners to things. we’ll inform every <div> within the thực đơn headings to hear for mouse click on, mouse over, and mouse out occasions.To make it simpler to set the occasion listeners, we’ll want a utility routine that offers us again a reference to an object in a doc once we give the item’s title. This perform makes use of variable isNav6, which is a part of the DOM Utilities package deal launched in an earlier tutorial.

perform getObject( objName )
{
    if (isNav6)
    {
       return doc.getElementById( objName );
    }
}

As soon as now we have the item, we are able to add an occasion listener with a press release of this type:

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

…the place:

title
is the title of the occasion you need the item to hear for
functionName
is the title of the perform that can course of that occasion
useCapture
is a boolean that tells whether or not you wish to use occasion capturing (true) or occasion effervescent (false).

So, what seems like this in HTML:

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

…is achieved like this when utilizing the DOM:

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

We use the getObject perform from above to jot down a setup() perform so as to add the occasion listeners to every of the thực đơn <div>s, which have ids of m0, m1, and m2.

var nMenus = 3;perform setup( )
{
    var i;
    var obj;    for (i=0; i < nmenus; i++)
    {
        obj = getObject("m" + i);
        if (isNav6)
        {
            obj.addEventListener("mouseover", spotlight, false);
            obj.addEventListener("mouseout", dim, false);
            obj.addEventListener("click on", showMenu, false);
        }
    }
}

Now, now we have to jot down the spotlight(), dim(), and showMenu() capabilities. With a purpose to do that, we should first perceive the idea of a Node.

Nodes#section6

As we detailed in a earlier article, your paperwork are made up of “spare components” which can be nested inside each other. This HTML…

<physique>
<p>
   First Textual content
   <img src="image.png">
   <i>Extra Textual content</i>
</p>
</physique>

…has this construction:

  • A <physique>, which incorporates
    • A paragraph (<p>), which incorporates
      • the First Textual content
      • a picture (<img>)
      • and an italic (<i>) aspect which incorporates

When CSS-compliant browsers learn your HTML recordsdata, they analyze this construction and create a construction of nodes, which you’ll consider as little chunks of knowledge that describe your doc. The nodes for the HTML above may be diagrammed as proven under. The highest half of every node exhibits the nodeName, and the underside half exhibits the nodeValue. You’ll be able to click on the diagram to open up a window that exhibits a bigger model.Tree DiagramNodes additionally comprise details about their relationship to one another. Let’s have a look at these nodes as in the event that they have been members of a household tree.

  • Node B’s parentNode is node A.
  • Node B’s firstChild is node C, and its lastChild is node E.
  • Node B additionally incorporates a childNodes array that lists all its rapid kids, C, D, and E).
  • Node D has a previousSibling, which is node C, and a nextSibling, node E.
  • Since node C has no one to its left and no one instantly under it, its previousSibling and firstChild properties will each be null.

Chances are you’ll discover these relationships extra totally in a brand new pop-up window.We’re going to make use of the power to maneuver by way of this “household tree” of a doc’s nodes to seek out out which <div> a consumer clicked within the increasing thực đơn.For a fast quiz on nodes, see should you can reply these questions:

  1. Who’s node F’s
    parentNode?
  2. Who’s node A’s
    firstChild?
  3. Who’re node B’s
    nextSibling and previousSibling?

See the solutions

  1. Node E is node
    F’s father or mother.
  2. Node B is
    A’s firstChild
    (and likewise its lastChild).
  3. Node B is an solely
    little one, so its previousSibling and
    nextSibling are null.

Discovering the <div>#section7

When an occasion happens, the corresponding occasion listener perform is invoked. This perform needs to be written to count on one argument – an Occasion object. The occasion’s goal property is the one we’re keen on; it inform us which Node is the occasion’s meant goal.
Once we click on the phrases or the picture in a <div>, the goal that will get returned is definitely the textual content or the picture contained in 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.]
Due to this fact, now we have to jot down a perform which checks to see if the goal of the occasion we cross to it’s a DIV aspect (tag). If not, the perform retains taking a look at that node’s parentNode, and its father or mother, and so forth, till it finds a DIV aspect.

perform findOwner(evt)
{
    var node = evt.goal;
    whereas (node)
    {
        if (node.nodeType == Node.ELEMENT_NODE &&
                 node.nodeName == "DIV")
        {
                return node;
        }
        node = node.parentNode;
    }
    return null;
}

As soon as now we have the <div>’s node, we are able to change its properties, which we’ll must do for the spotlight() and dim() capabilities. Discover that we alter the form of the cursor when it strikes over the <div>. [This does not work in Internet Explorer.]

perform spotlight(evt)
{
    var obj = findOwner(evt);
    if (isNav6) { obj.fashion.cursor = "pointer"; }
    obj.fashion.shade= "#ff0000"; // pink
}perform dim(evt)
{
    var obj = findOwner(evt);
    if (isNav6) { obj.fashion.cursor = "default"; }
    obj.fashion.shade = "#000000"; // black
}

Implementing showMenu()#section8

All that is still now’s to implement the showMenu() perform, which expands and contracts the thực đơn. The road numbers within the code under are for reference solely.

 1 perform showMenu(evt)
 2 {
 3        var proprietor = findOwner(evt);
 4 
 5        var divNum;
 6 
 7        divNum = proprietor.attributes.getNamedItem("id").nodeValue;
 8 
 9        divNum = parseInt(divNum.substr(1));
10 
11        if (getIdProperty("s" + divNum, "show") != "block")
12        {
13                setIdProperty("s" + divNum, "show", "block");
14                doc.photos["i" + divNum].src = "https://alistapart.com/article/domtricks2/minus.png";
15        }
16        else
17        {
18                setIdProperty("s" + divNum, "show", "none");
19                doc.photos["i" + divNum].src = "https://alistapart.com/article/domtricks2/plus.png";
20        }
21 }

Listed here are the traces of curiosity:

Line 3
As within the spotlight() and dim() capabilities,
we first have to seek out the “proprietor” of the press
occasion.
Line 7
A node’s attributes property offers a listing of
all of the tag’s attribute=worth pairs. It’s
listed by string, so we have to use the getNamedItem()
methodology to seek out the id attribute’s worth (given by
the nodeValue property).
Line 9
Since we’ve cleverly named all of the <div> tags
with ids like m0, m1, and so forth., we use
the substr methodology to extract the digit.
Line 11
Checks to see if a submenu is already displayed by
taking a look at its show property.
Traces 13-14, 18-19
We’ve additionally numbered the ids of the submenus and
the pictures, so it’s straightforward to alter their properties and
picture sources.

It’s a whole lot of code, however when you perceive it, you’ll be ready to control nodes for very highly effective results. Let’s summarize:

Abstract#section9

You employ the addEventListener() perform to make a doc object react to occasions moderately than having to make use of onOccasion= handlers within the tags. Chances are you’ll have a look at these occasions as they’re handed down from the doc to the the goal (seize), or as they’re handed up from the goal to its enclosing components (effervescent).When the occasion listener perform is invoked, you get an Occasion object that tells you the goal for which the occasion was destined. This goal might not all the time be the item whose properties you want to have an effect on, so it may be essential to stroll by way of the goal node’s “household tree” till you discover the node you need.Having the ability to connect occasion listeners to a doc’s objects is a superb comfort; realizing learn how to exploit the hierarchy of a doc’s nodes offers us immense energy. we’ll be taught extra about that within the subsequent tutorial.

Leave a Comment