jQuery Selector Chain Conditions

There has been a few times while writing a few jQuery plugins, that I came across a condition that basically does the same thing in both the if and else, and it always bothers me. I always wondered if their was a way to condense such a condition and help lower my file size, and after a little bit of tweaking I figured it out.

Take this scenario for instance:

The Problem:

if(animate == true){
    $('#someElm').animate({
        width:'512px',
        height:'512px'
    });
}else{
    $('#someElm').css({
        width:'512px',
        height:'512px'
    });
}

We have a bool variable (animate) that we condition against to either animate or set our element’s (#someElm) width and height. So why is the above bad exactly?

  • Wasted bytes in our script by using this if/else condition.
  • We have to use two selectors that point to the same element.
  • Both conditions are altering the same styles thus it’s again a waste of script bytes.

Hopefully you look at the above little piece of code in shame as much as I do now, and ponder on how one could possibly condense such a condition?

The Solution:

$('#someElm')[(animate == true) ? 'animate' : 'css']({
    width:'512px',
    height:'512px'
});

In the above solution, we have inserted ([…]) an area that we can use to condition our jquery chaining. So in the above solution I have opened this condition area up, and conditioned our bool animate variable again. Depending on the results from our bool animate variable, our selector chooses to either use the animate or css in our chain.

So in a nut shell we have solved the following:

  • No more wasteful if/else condition.
  • No more need for two selectors.
  • The values that are either set via “animate” or “css” are only declared once.

Thanks!

(If you wanted, you could take this optimization a step further by learning how to sum up repeated style values.)

Here is the artice on how to sum up repeated style values when using jquery animate or css.

Devin R. Olsen

Located in Portland Oregon. I like to teach, share and dabble deep into the digital dark arts of web and game development.

More Posts

Follow Me:
TwitterFacebookGoogle Plus