Setting a threshold on jQuery ajax callbacks using prefilters

This is a cross post from my company’s blog.

Skip straight to the demo.

When developing interfaces that include ajax functionality there will come a time when you will be showing some sort of loading animation and it will only show for a split second since the ajax call finished so fast.  This can cause the user to be disoriented since they aren’t exactly sure what popped up.  It can be beneficial to slow down the interface so the user can see everything that is going on.

In jQuery 1.5, there is now a way to extend the $.ajax method.  There are three different ways to extend $.ajax: prefilters, converters, and transports.  I am going to use prefilters which the jQuery documentation describes as “generalized beforeSend callbacks to handle custom options or modify existing ones”.  I’m not going to go into details about what a prefilter is since the documentation does a pretty good job.

Instead of setting up timeouts and clearing them out, I am wanting to pass a custom option to the ajax method.  Here is what I am trying to go for:

$.ajax(url, {
    ...
    successThreshold: 3000,
    ...
})

The successThreshold option is my custom option.  The time passed into it will be the minimum amount of time it takes before the success callback gets called.  Now that I have my custom option, I can access it and modify the other options in my prefilter.

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (originalOptions.successThreshold &&  $.isFunction(originalOptions.success)) {
        var start, stop;
        options.beforeSend = function () {
            start = new Date().getTime();
            if ($.isFunction(originalOptions.beforeSend))
                originalOptions.beforeSend();
        };
    
        options.success = function (response) {
        var that = this, args = arguments;
        stop = new Date().getTime();

        function applySuccess() {
             originalOptions.success.apply(that, args);
        }

        var difference = originalOptions.successThreshold - (stop - start);
        if (difference > 0)
            setTimeout(applySuccess, difference);
        else
            applySuccess();
        };
    }
});

The first thing I do in the prefilter is check to make sure both the successThreshold and success function are set.  I then override the beforeSend option in order to get the time before the ajax call starts.  In order to keep the success callback from firing before the threshold, the time difference needs to be calculated.  If the call didn’t take longer than the difference then set a timeout for the remaining time.  Otherwise just call the success callback immediately.

I have seen other solutions to this and all of them seem to set timeouts and clear them in different functions and it would have to be repeated for every call.  This can be defined in one place and used on any ajax call in the application.

I have added the code to my Github repository.  This demo shows the code in action.

Setting a threshold on jQuery ajax callbacks using prefilters

jQuery Extension: toggleText() method

Skip straight to the demo.

Here’s a situation I have run into multiple times: I have a hidden area that is toggled by a link.  The link will usually say “Show *”, and once it is clicked it will say “Hide *”.  I would usually just check the text when the link is clicked and switch it.  Similar to the following:

$("a").click(function() {
    var $self = $(this);
    if ($self.text() == "Show items")
       $self.text("Hide items");
    else
        $self.text("Show items");
});

It would get tedious to add this to every link that toggled the view on an element.  In order to make it easier on myself I threw together a little extension for jQuery.  You pass it 2 string values representing the text that you would like to toggle.  Here is an example usage that does the same thing as the code block above:

$("a").click(function() {
    $(this).toggleText("Show", "Hide");
});

The extension looks for the first value in the element’s text and if it exists, it is replaced with the second value.  If the first value doesn’t exist in the element’s text, it looks for the second value in the text and replaces it with the first value.   Here is the source:

jQuery.fn.toggleText = function (value1, value2) {
    return this.each(function () {
        var $this = $(this),
            text = $this.text();

        if (text.indexOf(value1) > -1)
            $this.text(text.replace(value1, value2));
        else
            $this.text(text.replace(value2, value1));
    });
};

To see it in action, you can view the demo.

jQuery Extension: toggleText() method

Using jQuery and YQL to get an RSS feed from a site

I forgot to post a link to this earlier, but I wrote a blog post on using jQuery and YQL to get an RSS feed from a web site. The code uses YQL to grab the content of the external site and then jQuery to find a link tag pointing to the location of the RSS feed. This is similar to how Firefox displays the RSS feed icon in the address bar.

Check out the full post here.

Using jQuery and YQL to get an RSS feed from a site

jQuery Custom Selector for selecting elements by exact text :textEquals

I just finished up writing another short blog post over on my company’s development blog covering a jQuery custom selector I wrote to find elements based on their exact text.  There was a particular case where I needed to select elements in jQuery based on their exact text and not on whether the text contained a certain string.  That ruled out the possibility to use the built in contains() method.

Lanit Development Blog – jQuery Custom Selector for selecting elements by exact text :textEquals

jQuery Custom Selector for selecting elements by exact text :textEquals