jQuery Plugin: Live Query

My hear is exploding with happiness and joy at the existence of Brandon Aaron. He has built a sweet jQuery plugin (Live Query) that reduces complexity in Ajax and general DOM manipulation coding by a great deal (when it comes to applying behaviors). First, let me tell you the problem (if you don’t already know):

Say I build a web application where I want to assign an onClick event to an <a> tag. In jQuery I’d do it like this:

First the HTML:

<a href="another.html" class="another">Grab Another!</a>

<ul>
  <li><a href="whee.html" class="whatever">Bork</a></li>
  <li><a href="whee.html" class="whatever">Bork</a></li>
  <li><a href="whee.html" class="whatever">Bork</a></li>
</ul>

Now lets do up the JavaScript:

$(document).ready(function(){
  $('a.whatever').bind('click',function(){
    alert('ZOMG Hai');
    return false;
  });
});

Simple, right? Yeah. It is. Nothing new. Now…say that I manipulate the DOM and add in another <a> tag with the class “whatever” that I want the same even applied (with or without Ajax, doesn’t matter). Here’s what I would have had to do in the past:

$(document).ready(function(){
  $('a.another').bind('click',function(){
    $('ul').append('<a href="whee.html" class="whatever">Bork</a>');

    $('a.whatever').bind('click',function(){
      alert('ZOMG Hai');
      return false;
    });

    return false;
  });
});

See that? Kinda complex. Things become quite complex when you begin doing Cross Domain Scripting via Remote JavaScript calls (which is what is heavily used in one of the apps I have done front-end development for).

The Live Query plugin is a beautiful thing as it “auto-magically” binds events to dynamically added elements within the page as they appear! So ALL of that JavaScript from both examples becomes:

$(document).ready(function(){
  $('a.whatever').livequery('click',function(){
    alert('ZOMG Hai');
    return false;
  });

  $('a.another').bind('click',function(){
    $('ul').append('<a href="whee.html" class="whatever">Bork</a>');
    return false;
  });
});

Yup. That’s it. Bind a livequery event to an element and as elements that match appear on the page…BAM! The event is applied.

There are some more advanced things you can do with the plugin and you can find those out at the Live Query site.