jQuery snippet to Ajaxify your Website

This click event brings the page via AJAX and filters only the content of the requested page. The downside of this approach is that the whole page is requested and then filtered by the jQuery selector.

This is a short tutorial using AJAX. I know that this may be a little old, or that maybe somebody has posted this before, but I wanted to show how easy it is “ajaxify” an entire website with just a few lines of code. What we can assume is that we have main a container that changes on every page.

(function($){
   $(document).ready(function(){
       var containerId = '#container',
       $container = $(containerId);
       $('a').live('click', function(e){
              $container.load($(this).attr('href') + '  ' + containerId);
              e.preventDefault();
        });
   });
})(jQuery);

What the previous lines of code do is get the element that changes on the page, then add the click event in all the links. This click event brings the page via AJAX and filters only the content of the requested page. The downside of this approach is that the whole page is requested and then filtered by the jQuery selector; however, once the page is requested it gets cached by the browser.