I spent a few hours yesterday trying to solve a jQuery problem that I was having…until I came across the excellent Live Query Plugin by Brandon Aaron which had already solved it for me. First, the blurb is:
Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated. [from Docs]

So, why would you need Live Query? In cases where you are dynamically adding elements to a page (i.e. DOM) using jQuery, you may want events attached to them. So, for example, I have a page that has been loaded. In response to user actions, I want to add a link that, when clicked on, triggers a “click” event. Because this link element has been generated dynamically, it won’t match any of the CSS declarations or have the same behaviours of elements which were there when the page loaded.
You can see a live (and very simple) example of this. The code behind the example is:
$(document).ready(function()
{
/*
Without Using Live Query:
*/
$('#add_new_box').click(function(){
$('#box_holder').append('<div class="new-box"><a id="add-again" href="#">Add Smaller</a></div>'); });
// a problem here - this doesn't fire as expected...
$('#add-again').click(function(){
$('#add_new_box').append('<div class="small-box"></div>');
});
/*
Using Live Query:
*/
$('#lq_add_new_box').click(function(){
$('#lq_box_holder').append('
<div class="lq-new-box"><a id="lq_add-again" href="#">Add Smaller</a></div>');
});
$('#lq_add-again').livequery('click', function(){
$('#lq_add_new_box').append('<div class="small-box"></div>');
});
}); // end document.ready(function)
In the example, the first link clicked adds a <div> with a link inside it. This new link, when clicked, should add a smaller yellow box. However, because the “Add Smaller” link was added dynamically, it does not have the click behaviour associated with it. It’s here that Live Query comes in.
In the second part of the example, Live Query is used to bind a click event to the link that was dynamically added. This ensures that the (my) expected behaviour of clicking the link in the red box and having a smaller yellow box appear goes to plan.
Having a web application be as responsive as possible is a target that should always be set. Doing so can be achieved in lots of ways, one of them being to minimise the number of page reloads the user needs to sit through. For what I am working on at the moment, Live Query just added a big lump of responsiveness to the interface. A great jQuery plugin.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=453fe09b-0739-4a67-bc50-1d71cb94e510)
Social?