edit delete favorite
Posted by jimbojw on Oct 09, 2007
Built on Scriptaculous Autocompleter.local object, this class allows you to inject Google Suggest suggestions into any text field (input with type="text"). In the example, the input has an id of "searchBox" and the auto-populated dropdown div has an id of "searchBoxSuggestions"
GoogleSuggestAutocompleter = Class.create();
Object.extend(Object.extend(GoogleSuggestAutocompleter.prototype, Autocompleter.Local.prototype), {
    cache: {},
    getUpdatedChoices: function() {
        var tok = this.getToken().toLowerCase();
        if (this.cache[tok]) return this.sendRPCDone( null, tok, this.cache[tok] );
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'http://www.google.com/complete/search?hl=en&client=suggest&js=true&q=' + encodeURIComponent(tok);
        document.body.appendChild(script);    
    },
    sendRPCDone: function( meh, tok, list ) {
        if (!list) return this.updateChoices( '<ul></ul>' );
        if (!this.cache[tok]) this.cache[tok] = list;
        var values = list.collect( function(v) { 
            return '<b>'+v.slice(0, tok.length)+'</b>'+v.slice(tok.length);
        });
        this.updateChoices( '<ul><li>' + values.join('</li><li>') + '</li><ul>' );
    }
});
 
var frameElement, google = {};
 
Event.observe(window, 'load', function(event) {
 
    google.ac = new GoogleSuggestAutocompleter( "searchBox", "searchBoxSuggestions", null, { minChars: 1 } );
    
}, 'false');
 
Must be logged in to add a comment or review

Comments

eric on Oct 10, 2007
This is so slick. I love scraping data from the Mighty Google - but what is the practical application here?
jimbojw on Nov 07, 2007
Well, one practical application is mind reading. That is, even though we don't know how Google comes up with the suggestions, you can be certain that at least a modicum of thought has been put into what to display. So for a site which aims to show releva
Please submit any bugs/features and report abuse. Thanks!
Spacer
Spacer
Spacer
Top Users
Spacer
Top Tags
Spacer