spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / ncz / column2 / 1 current pageTo page 2To page 3To page 4
[next]

Business Systems Analyst
Professional Technical Resources
US-OR-Portland

Justtechjobs.com Post A Job | Post A Resume
Developer News
Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next

Creating an Autosuggest Textbox with JavaScript, Part 2

By Nicholas C. Zakas.

In the first part of this series, you learned how to create type ahead functionality in a textbox, which presents the user with a single suggestion for what they've already typed. This article builds upon that functionality by adding a dropdown list of multiple suggestions. To do so, you'll extend the autosuggest control and suggestion provider class definitions.

Creating the Dropdown List

The dropdown suggestion list is nothing more than an absolutely-positioned <div/> containing several other <div/>s. It's placed directly under the textbox to create the appearance of a dropdown menu (see the image below).

The HTML for the suggestion list in the image above looks like this:

<div class="suggestions">
    <div class="current">Maine</div>
    <div>Maryland</div>
    <div>Massachusetts</div>
    <div>Michigan</div>
    <div>Minnesota</div>
    <div>Mississippi</div>
    <div>Missouri</div>
    <div>Montana</div>
</div>

Of course, some CSS is needed to make the dropdown list function properly. The outermost <div/> has a class of "suggestions," which is defined as:

div.suggestions {
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid black;
    position: absolute;
}

The first two lines of this CSS class are for browsers that support two forms of box sizing: content box and border box (for more information, read http://www.quirksmode.org/css/box.html). In quirks mode, Internet Explorer defaults to border box; in standards mode, IE defaults to content box. Most other DOM-compliant browsers (Mozilla, Opera, and Safari) default to content box, meaning that there is a difference in how the <div/> will be rendered among browsers. To provide for this, the first two lines of the CSS class set specific properties to border box. The first line, -moz-box-sizing, is Mozilla-specific and used for older Mozilla browsers; the second line is for browsers that support the official CSS3 box-sizing property. Assuming that you use quirks mode in your page, this class will work just fine (if you use standards mode, simply remove these first two lines).

For the other two lines of the suggestions CSS class, simply add a border and specify that the <div/> is absolutely positioned.

Next, a little bit of formatting is need for the dropdown list items:

div.suggestions div {
    cursor: default;
    padding: 0px 3px;
}

The first line specifies the default cursor (the arrow) to be displayed when the mouse is over an item in the dropdown list. Without this, the cursor would display as the caret, which is the normal cursor for textboxes and Web pages in general. The user needs to realize that the dropdown item is not a part of the regular page flow and changing the cursor helps define that. The second line simply applies some padding to the item (which you can modify as you wish).

Lastly, some CSS is needed to format the currently selected item in the dropdown list. When an item is selected, the background will be changed to blue and the color will be changed to white. This provides a basic highlight that is typically used in dropdown menus. Here's the code:

div.suggestions div.current {
    background-color: #3366cc;
    color: white;
}

Now that you understand how the dropdown list will be built, it's time to begin scripting it.

Scripting the Dropdown List

Creating the DOM representation for the dropdown list is a multi-stage process. First, a property is needed to store the <div/> because various methods of the AutoSuggestControl need access to it. This property is called layer and is initially set to null:

function AutoSuggestControl(oTextbox, oProvider) {
    this.layer = null;

    this.provider = oProvider;
    this.textbox = oTextbox;
    this.init();
}

The layer and the other parts of the dropdown list DOM will be created after you define a few simple methods to help control its behavior. The simplest method is hideSuggestions(), which hides the dropdown list after it has been shown:

AutoSuggestControl.prototype.hideSuggestions = function () {
    this.layer.style.visibility = "hidden";
};

Next, a method is needed for highlighting the current suggestion in the dropdown list. The highlightSuggestion() method accepts a single argument, which is the <div/> element containing the current suggestion. This method's purpose is to set the <div/>'s class attribute to "current" on the current suggestion and clear the class attribute on all others in the list. Doing so provides a highlighting effect on the dropdown list similar to the regular form controls. The algorithm is quite simple: iterate through the child nodes of the layer. If the child node is equal to the node that was passed in, set the class to "current," otherwise clear the class attribute by setting it to an empty string:

AutoSuggestControl.prototype.highlightSuggestion = function (oSuggestionNode) {

    for (var i=0; i < this.layer.childNodes.length; i++) {
        var oNode = this.layer.childNodes[i];
        if (oNode == oSuggestionNode) {
            oNode.className = "current"
        } else if (oNode.className == "current") {
            oNode.className = "";
        }
    }
};

With these two methods defined, it's time to create the dropdown list <div/>. The createDropDown() method creates the outermost <div/> and defines the event handlers for the dropdown list. To create the <div/>, use the createElement() method and then assign the various styling properties:

AutoSuggestControl.prototype.createDropDown = function () {

    this.layer = document.createElement("div");
    this.layer.className = "suggestions";
    this.layer.style.visibility = "hidden";
    this.layer.style.width = this.textbox.offsetWidth;
    document.body.appendChild(this.layer);


    //more code to come
};

The code above first creates the <div/> and assigns it to the layer property. From there, the className (equivalent to the class attribute) is set to "suggestions", as is needed for the CSS to work properly. The next line hides the layer, since it should be invisible initially. Then, the width of the layer is set equal to the width of the textbox by using the textbox's offsetWidth property (this is optional dependent on your individual needs). The very last line adds the layer to the document. The next step is to assign the event handlers.


home / programming / javascript / ncz / column2 / 1 current pageTo page 2To page 3To page 4
[next]



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview · Controllers: Programming Application Logic - Part 2 · How to Use JavaScript to Validate Form Data
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Choosing the Right Online Backup Provider · Mother Avaya Nurtures Her Technology Partners · Software as a Service a Winning Model for Hotspot Provider

Created: March 27, 2003
Revised: April 08, 2005

URL: http://webreference.com/programming/javascript/ncz/column2/1