Unobtrusive JavaScript on Dynamic Content

I’m working on a web application outside of my FamilySearch work that requires a lot of AJAX behavior. I have been using Prototype with Rails’ Prototype Helpers, but this is beginning to become a unwieldy.

The content I load can get very large with TONS of inline JavaScript, so in an effort to trim down the html and improve performance, I’m beginning to use Unobtrusive JavaScript methods. While I do this, I’m also doing a migration to jQuery.

I had seen a lot of code examples that looked like this:

jQuery(function($) {
  $('a.sidenote').click(function() {
    var href = $(this).attr('href');
    window.open(href, 'popup',
      'height=500,width=400,toolbar=no');
    return false;
  });
});

This seemed to work for event listening on elements that were loaded as the page loads, but I have lots of content that is loaded via AJAX methods after the document loads. I needed something that would bind the listeners not only at the time the document loaded, but would continue to bind event listeners to new content that matched the given selectors.

I later discovered the “live” method. This does exactly what I want it to do. Instead of just registering a click, I call live, so the above example would change to:

jQuery(function($) {
  $('a.sidenote').live('click',function() {
    var href = $(this).attr('href');
    window.open(href, 'popup',
      'height=500,width=400,toolbar=no');
    return false;
  });
});

This doesn’t require a big change in code, but the approach is much more powerful and truly allows you to make your JavaScript unobtrusive.