Posts Tagged ‘href’

When designing a rich user interface with JQuery it is very useful to replace default hyperlink functionality with ajax calls. The first method will turn the <a> functionality into an ajax call using the “href” attribute as source. The second method will do the same, but will ask “Are you sure?” first (very usefull for deletes etc…).

The ajaxReload var can then be set to a function that would handle the ajaxCall. These methods would usually be located in a ‘common.js’ file.

// GLOBAL VARS
var ajaxReload = function() { };

$(".ajaxCall").live("click", function(e) {
    e.preventDefault();
    $.get($(this).attr("href"), ajaxReload);
});

$(".yesNoAjaxCall").live("click", function(e) {
    e.preventDefault();
    if (confirm('Are you sure?')) {
        $.get($(this).attr("href"), ajaxReload);
    }
});

The reason behind using ‘live’ instead of ‘bind’ or ‘click’ is because I want to bind all future loaded ‘a’ tags too. Usually ‘bind’ or ‘click’ will only find the static ‘a’ tags that are available on page load.