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/

jQuery Extension: removeClassExcept() method

Quick tip: Get a darker/lighter version of a hex value

This tip is for Chrome users.  Inside of the Chrome Developer Tools you can view the color value of an element by inspecting the element.  You will see something like the following:

Hex value of the color

If you click on the colored box, the value will rotate through the other possible values (hex, rgb, hsl).  Click on the box until you see the hsl of the color.  The last value is for “lightness”.  Changing the percentage makes the color lighter (higher percentage) or darker (lower percentage).  After changing the value just click on the colored box again to get back to the hex color value.

The last percentage value is for "lightness"
Quick tip: Get a darker/lighter version of a hex value

Recreating Google+ Expanding Image Stack

Skip straight to the demo

After taking some time to browse around Google+ I noticed a cool effect on the albums page when hovering over an album. If the album had multiple images in it, the stack would expand to show the first 3 images inside the album. You can see an example of it here: https://plus.google.com/photos/105135327491673313070/albums.

I thought it would be neat to try and reproduce this effect. This example will work in Chrome, Firefox 4+, and Safari 4+.

Step 1 – Get images

The only thing we need to do in step 1 is get 3 images of the same size and put them into a block element.  I grabbed 3 images from my Google+ account and put them in a div with the id of “photo-stack”.

<div id="photo-stack">
    <img src="https://lh3.googleusercontent.com/-khtZ0GBqcOI/Th2kD8vv0ZE/AAAAAAAAACU/rd3t2O6QI-o/s195-c/BVI2008" />
    <img src="https://lh3.googleusercontent.com/-ZpghGAz-jZE/Th2kECfNChI/AAAAAAAAACI/VAtLWAuUbf0/s195-c/photo.jpg" />
    <img src="https://lh4.googleusercontent.com/-xcrH8Z9qHqI/Th2kEMhqQ1I/AAAAAAAAACA/jL8ZZTTpqA4/s195-c/photo.jpg" />
</div>

View Step 1

Step 2 – Stacking

Now that we have our 3 images let stack them on top of each other.  This is accomplished by positioning each of them absolutely on top of each other.


#photo-stack { position: relative;}

#photo-stack img { position: absolute; top: 0; left: 0;}

That looks good, but I want the first image in the DOM to appear on top.  In that case we need to set the z-index of each image.  I am going to use the nth-child property so we don’t have to add classes to each image.


#photo-stack img:nth-child(1) { z-index: 3;}

#photo-stack img:nth-child(2) { z-index: 2;}

#photo-stack img:nth-child(3) { z-index: 1;}

Now the first image is on the top!

View Step 2

Step 3 – Moving

Let’s start working on the animation.  The animation has 3 parts to it: movement of the images, rotation of the images, and the size of the images.

We can handle the movement of the images by using the translate value of the transform property.  We are going to use the nth-child property just like we did in the last step in order to target each image individually.

Translate takes 2 values for the x and y movement.  Since the second image isn’t moving we are only going to move the first and last images.


#photo-stack:hover img:nth-child(1) {
    -webkit-transform: translate(-50px, 0px);
}
#photo-stack:hover img:nth-child(3) {
    -webkit-transform: translate(50px, 0px);
}

View Step 3

Step 4 – Rotating

Now that we have the images moving apart we can rotate the outer image.  Rotate only takes 1 argument for the amount of degrees you want to rotate the element.  Once again the middle image is not being rotated so we will not worry about it.


#photo-stack:hover img:nth-child(1) {
    -webkit-transform: rotate(5deg);
}
#photo-stack:hover img:nth-child(3) {
    -webkit-transform: rotate(-5deg);
}

We are getting close!  View Step 4

Step 5 – Scaling

The images need to grow a little in size when they are spreading apart.  By using the scale property we can pass in a value to change the size of the image (1 being 100%).


#photo-stack:hover img:nth-child(1) {
    -webkit-transform: scale(1.1);
}
#photo-stack:hover img:nth-child(2) {
    -webkit-transform: scale(1.1);
}
#photo-stack:hover img:nth-child(3) {
    -webkit-transform: scale(1.1);
}

View Step 5

Step 6 – Animating

In order to get the transforms to animate when hovering, only 1 line of code needs to be added.  The -webkit-transition line takes 3 arguments: property to animate, amount of time, and animation timeline.  In our case we want to animate the -webkit-transorm property for .25 seconds and have a linear timeline.


#photo-stack img {  -webkit-transition: -webkit-transform .25s linear;}

View Step 6

Step 7 – Cleanup

The look can be cleaned up a little by applying some additional styles.  Now it looks like a real stack of photos!

View Final Demo

Let me know what you thought of the tutorial or if you put this to use on one of your sites!

Recreating Google+ Expanding Image Stack

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

Chrome Dev Tools at Google I/O 2011

If you are still using Firefox just for Firebug, I bet you will switch to Chrome after watching this video.  I used to stick with Firefox while developing since Firebug was so good at what it did, but Google is doing great things with their dev tools.  The following talk is from Google I/O 2011 featuring Paul Irish and Pavel Feldman.  The talk mostly covers new features, but you can take a look at their docs site for all the features.

The video clocks in at just over 40 mins but it is well worth the time.

Chrome Dev Tools at Google I/O 2011

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

iOS 4.2 features that I have been waiting for

So I finally got around to downloading the new iOS 4.2 update tonight and after reading through the list of updates I found a couple features that haven’t been talked about too much.  It seems all the hype has been around the AirPrint and AirPlay functionality.  The features I am happily looking forward to are:

  • Find text on the web page in Safari
  • New SMS/MMS text tones and the ability to set custom tones per contact

Find text on the web page in Safari

I can’t recall the amount of times I have loaded a web page in mobile Safari and wished this feature existed.  It seems this feature would be very important for small screen devices since skimming large amounts of data is not easy.  I’m not sure how this will look in the UI, but I will update this post once I get the update installed.

After I got the update installed I loaded up Safari to check out the new find feature.  I loaded up the Apple website and started poking around to try and find the feature.  The first button I tried was the middle button on the bottom bar that looks like a box with an arrow coming out of it.  It was the wrong choice, but it did show me where the “Print” button was.  I then tried clicking each button including the URL and Google search and still couldn’t find where the feature was.

The new bar above the keyboard
The new bar above the keyboard

I then opened the Google search to see if anyone else is having problems.  As soon as I started typing a new bar appeared right above the keyboard saying how many matches there were on the current page.  Apparently you have to use the Google search feature to find items on the current page.  This to me doesn’t make sense at all.  How is that intuitive?  I click “Google” to find what is on the page?  Weird.

Scrolling down past the Google results
Scrolling down past the Google results

After typing in the term to find on the page, you then have to scroll down past all the results that Google returned.  Again, this seems a little out of place.  Finally, clicking on the “Find ****” line opens up the interface for the find feature.  The term you are searching for is highlighted similar to how the desktop version of Safari does it.  The term is highlighted in a yellow bubble.  A new toolbar at the bottom allows advancing through the matches and there is a “Done” button for when you are finished.

Search term is highlighted and bar at the bottom to advance matches
Search term is highlighted and bar at the bottom to advance matches

Overall I am not a big fan of how the feature is implemented.  I feel Apple could have done a better job with the user experience.

New SMS/MMS text tones and the ability to set custom tones per contact

This is another one of those features where you ask “Why wasn’t that in version 1.0?”.  It seems like it would be so easy to add this feature in, but apparently it never seemed important enough to Apple.  I have always been disappointed with the lack of choices for tones for SMS/MMS.  Not only that, there are only 1 or 2 that are any good and the others are just annoying.

Having the ability to assign certain tones per contact will nice.  However, if the new tones aren’t any good then you will be stuck using the annoying tones.

I still wish Apple would add the ability for custom SMS/MMS tones.  How hard would it be?  They could even sell them for $1 and make a killing.  I would assume they are eventually going to go this route.

iOS 4.2 features that I have been waiting for

Intel should stick to processors

I was taking some old clothes up to the local Goodwill to donate them and decided to browse around while I was there.  I found myself in the back of the store where they keep all the electronics, secretly hoping to find a good deal on something.  As I was skimming the less than desirable selection, something caught my eye.  At first I thought it was one of the original PS3 controllers (see below), but after taking a closer look I actually started laughing out loud.  It is a wireless controller from Intel that is a god awful shape.  The controller is apparently part of a series of wireless devices from Intel as you can see on front of the box.

I am not sure Intel is ready for the game peripheral market just yet.

Intel should stick to processors