09 Aug 2009 No Comments
AJAX jQuery link binding
When building an AJAX site often there will be a large amount of links that need to be processed in a specific way. Namely links will need to load content and replace a DOM element.
A very basic way of doing this would be to do the following:
$(document).ready(function() { $('a').livequery('click', function() { var $el = $(this); var href = $el.attr('href'); $('#content').load(href); return false; }); });
Now, lets run through this.
$(document).ready(function() { //snipped code });
jQuery has a great ability to run as soon as the DOM is ready, not just once it has loaded. Every inside this codeblock will be run as soon as the DOM is ready.
$('a').livequery('click', function() { var $el = $(this); var href = $el.attr('href'); $('#content').load(href); return false; });
Here we are using the amazing plugin livequery – which allows for binding/firing callbacks on elements loaded after the DOM has loaded (i.e. via AJAX) – to bind the click event on all links. From there we load content via ajax and replace the contents of the DOM element with the id=”content”.
There are a couple of problems with this method:
- It’s slow. It has to find and loop through all links on the site, and everything loaded via AJAX thereafter and bind their click events.
- Because of the time and processing required to bind all the links there will (for a small amount of time) be unbound links and if a user were to click on an unbound link the page will load as per normal, which in the case of a pure AJAX site is abnormal (link unstyled content).
Now, let’s look at an alternative solution:
$(document).ready(function() { $('body').bind('click', function(event) { var $el; if($(event.target).is('a')) { $el = $(event.target); } else { $el = $(event.target).parents('a'); } if($el.is('a')) { var href = $el.attr('href'); $('#content').load(href); return false; } )}; });
Now, instead of binding all the links in the document we are binding the body element and then checking what element is clicked. If the element is a link then it is processed as per the previous example.
- The benefits of this method is that the livequery plugin is not needed (less additional overhead).
- AJAX loaded content will automatically be bound because its parent element is bound.
- It’s fast. With only 1 element to be bound there is very little processing required. The only processing required is when a link is actually clicked.
Well, there you have it, the code is obviously simplified. There are almost limitless possibilities to enhance this code and or refactor it to be used for a different purpose. I’ll leave it up to you to use it as you will. If you find any errors or have any suggestions let me know.