jQuery LiveSearch


A fun blog post popped up yesterday in which John Nunemaker ported a Quicksilver-style Live Search to jQuery. Taking a look at his code, I decided to have a little fun and re-port it to jQuery – trying to use the functional style that jQuery promotes. I think the end result is quite simple and elegant.

The final code – compare with John’s port:

  1. jQuery.fn.liveUpdate = function(list){
  2.   list = jQuery(list);
  3.  
  4.   if ( list.length ) {
  5.     var rows = list.children('li'),
  6.       cache = rows.map(function(){
  7.         return this.innerHTML.toLowerCase();
  8.       });
  9.      
  10.     this
  11.       .keyup(filter).keyup()
  12.       .parents('form').submit(function(){
  13.         return false;
  14.       });
  15.   }
  16.    
  17.   return this;
  18.    
  19.   function filter(){
  20.     var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
  21.    
  22.     if ( !term ) {
  23.       rows.show();
  24.     } else {
  25.       rows.hide();
  26.  
  27.       cache.each(function(i){
  28.         var score = this.score(term);
  29.         if (score > 0) { scores.push([score, i]); }
  30.       });
  31.  
  32.       jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
  33.         jQuery(rows[ this[1] ]).show();
  34.       });
  35.     }
  36.   }
  37. };

A couple points to note:

  • .liveUpdate() no longer takes an element ID – it now accepts any jQuery selector (this is the only notable API change that I made).
  • All state is stored in simple variables and accessed via closures, as opposed to as properties of an instance object.
  • Only one function is used – and that’s stored away within the function itself (greatly simplifying the resulting code).
  • DOM queries are only done once and cached up front.
  • .map() is used to simplify the creation of new arrays of information.

Posted: July 8th, 2008


If you particularly enjoy my work, I appreciate donations given with Gittip.

55 Comments (Show Comments)



Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question concerning the content of this post, please feel free to contact me.


Secrets of the JavaScript Ninja

Secrets of the JS Ninja

Secret techniques of top JavaScript programmers. Published by Manning.

Ukiyo-e Database and Search

Ukiyo-e.org

Japanese woodblock print database and search engine.


John Resig Twitter Updates

@jeresig

Infrequent, short, updates and links.


via Ad Packs