Monday, January 30, 2012

How to Make Javascript and Jquery Selectors function after Content is Refreshed with AJAX

So today I had another really specific problem while working on followtheproject.com. For my setup I have a group of <a> elements that are targeted by a jQuery selector, like $("a#id"), that was capturing their click() events and performing some ajax requests instead of going to a link. The return data for the ajax request reloads all of the <a> elements. The problem is that these newly loaded <a> elements are no longer targeted by the Jquery selector!

After some searching I found an extremely easy answer to solve this. The secret lies in jQuery's .live() function: http://api.jquery.com/live/

syntax:
selector.live( event, handler(eventObject) )

By wrapping event calls in the .live() function you are ensuring that all elements that match the selector, both now and in the future, will be targeted. This is different from regular selector and event functions because those are only applied to current elements that match the selector.

Old code 
$("a#id").click( function(e){ STUFF } );

New code
$("a#id").live('click', function(e){ STUFF });

For the lazy, here is the link to all of Jquery's event handlers: http://api.jquery.com/category/events/

Easy Peasy. The link will not always be redirected to the jQuery click event through the live() function, even after AJAX reloads the <a> elements! I wonder why the developer's of Jquery don't just build this into the normal click() and other event functions. Any performance hits would likely be worth the extra functionality.

4 comments:

  1. Hi Great tutorial,it was reallly helpful for us and helped me in teaching others,anyways thanks for this post!
    Java Training in Bangalore

    ReplyDelete
  2. Blog commenting is about leaving your blog comments at another blogger's blog at the end of their blog post, and by leaving your name and blog address, you may invite people to click on your link and direct them to your blog. This is a simple method to drive free traffic to your blog, and it is also recommended by many bloggers as a free traffic generation strategy. This strategy has also helped many new bloggers who are new to the blogosphere to start generate traffic to their blog. seo content

    ReplyDelete
  3. Thank you so much for ding the impressive job here, everyone will surely like your post. thekontent.de/

    ReplyDelete