skip to content

New Plugin: Live Query

2 min read

Live Query, previously called Behavior, 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.

For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX or a script.

    .livequery('click', function(event) {
        return false;

Once you add new A tags to the document, Live Query will bind the click event and there is nothing else that needs to be called or done.

When an element no longer matches a selector the events Live Query bound to it are unbound. Also, the Live Query can be expired by calling expire which will no longer bind anymore events and unbind all the events it previously bound.

Live Query can even be used with the more powerful jQuery selectors. The following Live Query will match and bind a click event to all A tags that have a rel attribute with the word “friend” in it. If one of the A tags is modified by removing the word “friend” from the rel attribute, the click event will be unbound since it is no longer matched by the Live Query.

    .livequery('click', function(event) {

Live Query also has the ability to fire a callback function when it matches a new element and another callback function for when an element is no longer matched. This provides ultimate flexibility and untold use-cases. For example the following code uses a function based Live Query to implement the jQuery hover helper method and remove it when the element is no longer matched.

            .hover(function() {
            }, function() {
    }, function() {

See It In Action

I’ve put together two simple demos that utilize both an event based and function based Live Query on unordered lists.

Get Live Query

Live Query can be downloaded from the Live Query project page.