Sunday, May 2, 2010

Working with AJAX? j Query’s .live() is your best friend

by Roman Leinwather

I have been working with jQuery ajax() or load() functions for quite some time. For those of you who do not use jQuery, these are the functions which you can use to achieve ajax calls. Today I am not going to describe how the ajax works but rather how you can interact with data which were brought by ajax call.

If you would try to apply simple .click() or hover() functions on elements which have been inserted into the page via ajax or simple by JavaScript after the page was loaded you would not succeed. Someone else would probably be able to describe much better what is happening at the background but I am just guessing that jQuery “makes a note” of current DOM element at the time of page load and anything which comes afterwords is unknown for it.

This is the time when .live() comes on scene. If you would like to apply for example fadeOut effect on click on the div with id=”ajax_box” which will be inserted into the page after some kind of page interaction you will be using this syntax.

$(function(){
  $('#ajax_box'.).live(click, function () {
    $(this).fadeOut();
  });
});

I think there is not need to describe the syntax. I see that the only difference is that the live function is a wrapping the function we want to apply. You could obviously apply different event handlers.

live() function will guarantee that even if you have or have not the element with the id “ajax_box” inside your html at the time the page loads you will be able to apply behaviors to it.