jQuery Extension: removeClassExcept() method

I came across a question on StackOverflow.com where the user wanted the ability to remove all classes from an element except certain ones.  For example if I had the following element

<div class="aa bb cc dd ee">Lorem Ipsum</div>

How would you go about removing all classes except for “aa” and “bb”?  One way would be to just set the class attribute to the classes you wanted to keep.


$("div").attr("class", "aa bb");

That’s easy enough.  Another way would be to use some built in jQuery methods.


$("div").removeClass().addClass("aa bb");

The previous code would remove all classes and then add back the ones that were needed.  That snippet could be put into a jQuery extension to make it easier to call.


jQuery.fn.removeClassExcept = function (val) {
    return this.each(function () {
        $(this).removeClass().addClass(val);
    });
};

$("div").removeClassExcept("aa bb");

That makes the code look cleaner.  One problem both of these solutions have is they don’t check to see if the class already exists before adding it.  On the Stack Overflow question, Brad Christie proposed a solution to handle the case where you didn’t want to add a class unless it already existed.  The updated extension now takes that into consideration.


jQuery.fn.removeClassExcept = function (val) {
    return this.each(function (index, el) {
        var keep = val.split(" "),  // list we'd like to keep
            reAdd = [],          // ones that should be re-added if found
            $el = $(el);       // element we're working on

        // look for which we re-add (based on them already existing)
        for (var i = 0; i < keep.length; i++){
            if ($el.hasClass(keep[i])) reAdd.push(keep[i]);
         }

         // drop all, and only add those confirmed as existing
         $el
            .removeClass()               // remove existing classes
            .addClass(reAdd.join(' '));  // re-add the confirmed ones
    });
};

Here is a jsFiddle showing the use of removeClassExcept(): http://jsfiddle.net/9xhND/1/

Advertisements
jQuery Extension: removeClassExcept() method

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 &amp;amp;&amp;amp;  $.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

jQuery Extension: radioClass() method

I recently ran into a method in the Ext javascript library called radioClass. This method will add one or more CSS classes to an element and remove the class(es) from the siblings of the element. I found that this would be helpful in jQuery since I find myself wanting to do something similar.

Check out the blog post on the Lanit Development Blog – jQuery Extension: radioClass() method

jQuery Extension: radioClass() method