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:

jQuery.fn.liveUpdate = function(list){
  list = jQuery(list);

  if ( list.length ) {
    var rows = list.children('li'),
      cache = rows.map(function(){
        return this.innerHTML.toLowerCase();
      });
      
    this
      .keyup(filter).keyup()
      .parents('form').submit(function(){
        return false;
      });
  }
    
  return this;
    
  function filter(){
    var term = jQuery.trim( jQuery(this).val().toLowerCase() ), scores = [];
    
    if ( !term ) {
      rows.show();
    } else {
      rows.hide();

      cache.each(function(i){
        var score = this.score(term);
        if (score > 0) { scores.push([score, i]); }
      });

      jQuery.each(scores.sort(function(a, b){return b[0] - a[0];}), function(){
        jQuery(rows[ this[1] ]).show();
      });
    }
  }
};

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


Subscribe for email updates

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.

John Resig Twitter Updates

@jeresig / Mastodon

Infrequent, short, updates and links.