Christian Heilmann

Progressively enhancing autocomplete

Friday, October 26th, 2007 at 11:14 am

I like Autocomplete as a design pattern. It allows you to find things a lot faster than using a normal search box and saves you having to go through a search result page. Autocomplete means progressively enhancing a normal search box to provide a faster and more channeled way to find information. Good autocomplete controls do that in a totally unobtrusive manner and load the extra information only on demand and when the user requires it.

However, there is another use case I haven’t seen covered properly yet: what if I want to offer a defined, small amount of options and a full search but not rely on JavaScript? The solution is to use a list of links followed by a search box:

Wouldn’t it be cool to use this as a fallback when JavaScript is not available and use this information to seed an autocomplete control when it is? Well, you can.

Naturally at work I keep running into the YUI Autocomplete control and this one has the option to use a JavaScript array or even a JavaScript function as the data source for the options. We can easily use this to get the information from the list of options:

function doAutoComplete(){
var optionsLinks = opts.getElementsByTagName(‘a’);
var ds = [];
for(var i=0;optionsLinks[i];i++){
var acDataset = new YAHOO.widget.DS_JSArray(ds);
acDataset.maxCacheEntries = 0;
var ac = new YAHOO.widget.AutoComplete(’s’,’autocompcontainer’, acDataset);

The thing about YUI autocomplete that always annoyed me is the amount of dependencies you have to include to get the whole thing working. This is of course by design as it builds on other parts of the YUI, but it was a bit of an annoyance to me. There is however a really cool way to make YUI controls load the YUI components necessary: you can use an object called YAHOO_config and define a listener method. This listener method gets called every time you include a YUI component and gets its name as a parameter. Couple this with dynamically created script nodes and you can call the dependencies one after the other:

function YAHOO_config_ac_run(o){
} else {
case ‘yahoo-dom-event’:
case ‘animation’:
case ‘autocomplete’:
var l = document.createElement(‘link’);
l.type = ‘text/css’;
l.rel = ‘stylesheet’;
l.href = ‘’;
function addJS(url){
var head = document.getElementsByTagName(‘head’)[0];
var s=document.createElement(‘script’);
s.src = ‘’ + url;
YAHOO_config = {

Putting it all together you get an autocomplete control with a list as a fallback. Try turning JavaScript on and off to see the difference.

Share on Mastodon (needs instance)

Share on Twitter

My other work: