Search code examples
jqueryjquery-chaining

adding 'if' logic to a jQuery chain


Let's say I have the following jQuery:

// pseudocode  :
$(this)
    .doSomething
    .doSomething
    .selectSomething
        .doSomething
        .animate({ 
            opacity: 1
        }, 150)
        .end()
    .selectSomethingElse
        .doSomething

I want the above to execute. However, if the browser is IE, I don't want the animate part to execute (due to IE being unable to animate objects with transparent PNGs and retain PNG transparency).

Is there anyway to maintain the nice chained jquery syntax but somehow skip the animate part based on some if logic (in this case testing for IE)?


Solution

  • You can do an each() and pass a function to it which handles the animation, that should work.

    $(this)
        .doSomething
        .doSomething
        .selectSomething
            .doSomething
            .each(function() {
                // Will return false on IE, true on others
                if(jQuery.support.opacity) {
                    $(this).animate({ 
                        opacity: 1
                    }, 150);
                }
            })        
        .end()
    .selectSomethingElse
        .doSomething