, ,

Yet Another AutoComplete Script (YAACS)

I've created yet another autocomplete script that suggests strings from a simple Array. At Ma.gnolia, we were using the built-in Rails autocomplete, which caused some serious slow-downs when you had thousands of tags. So we switched to the Yahoo UI autocomplete script (which is live as of this writing), but this can also be slow at times and it requires loading a number of additional YUI scripts that we don't use anywhere else in the site. That's some unneeded overhead (especially considering we're loading prototype w/ every page).

Here is an example of the new script:




So how do you use it?

  1. First, download the script and include it in your page. Make sure you've also included prototype.js.
  2. Create an array of suggestions (tags in this case).
  3. Add an input field to your page with an empty div underneath it for suggested input.
  4. Insert this Javascript code into your page UNDER the input field and suggestion node:
  5. new Autocomplete('tag_input', 'tag_suggestions', tags);

    Here we are passing in the id of the input field, the id of the suggestion div, and the tag array to the Autocomplete constructor.

  6. Add a little style. Here are the styles I'm using:
  7. <style>
        #tag_suggestions, #tag_input{
    		width: 400px;
    	}
    	#tag_suggestions{
    		background-color: #eeeeff;
    		position: absolute;
    		z-index: 9999999;
    		overflow: auto;
    		max-height: 200px;    
    	}
    	* html #tag_suggestions{
    		background-color: transparent;
    		height: 200px;    
    	}
    	#tag_suggestions a{
    		text-decoration:none;
    		color: #000;
    		display: block;
    		padding: .2em .5em;
    	}
    	* html #tag_suggestions a{
    		background-color: #eeeeff;
    	}
    	#tag_suggestions a.selected, #tag_suggestions a:hover{
    		background-color: #ffff00;
    	}
    </style>
    

If the autocomplete is being instantiated more than once in the same page, the selectors above should be changed to class names, rather than id names.

Let me know if you have any comments or suggestions!

Comments

Moiz said:
Nov 22, 2006 at 10:25 AM

Thanks for this great example.
I'm using it in my personal project.
I'm reading the data from a database, then i'm storing that data in an array.
The script i'm using to read data is in VB Script and your example uses JS.
Everything else is working fine except the statement "new Autocomplete('tag_input', 'tag_suggestions', tags);" is not working.

PLS kindly suggest any solutions.
Thanks.



Osh said:
Feb 14, 2008 at 08:55 PM

Nice code. Totally makes sense for a small set of items... why bother with trips to the server?

For my application I found it useful to tweak the regex to match the inputted text anywhere in a tag, not just at the beginning of a tag.

Thanks for sharing this.