Search code examples
javascriptjquerychaining

How to do a shorthand if-then in jQuery? Are these chainable?


Actually two questions:

I like the shorthand IF-ELSE in jQuery like so:

var some == true ? "it's true" : "it's false";   

Is there a corresponding IF-THEN, because this:

   var some == true ? "it's true" 

doesn't seem to work.

Also, would something like this be chainable in regular jQuery? Like so:

  some.addClass("hello")
      .find(".other").css("width","100px").end()
      // chained if
      .hasClass("one") ? some.css("border","1px solid red")
      .removeClass("hello")

Now that would be nice, wouldn't it? Is this possible?


Solution

  • There are a couple of plug-ins that allow you to chain if logic in jQuery -

    http://outwestmedia.com/jquery-plugins/conditional/

    $('div')
        .If('hasClass', 'myClass')
            .css('color', 'red')
        .Else('hasClass', 'anotherClass')
            .css('color', 'green')
        .Else()
            .css('color', 'blue');
    

    http://benalman.com/projects/jquery-iff-plugin/

    function my_test( x ) {
      return x === 'bar';
    };
    
    $('div')
      .append( '1' )
      .iff( my_test, 'foo' )
        .append( '2' )
        .end()
      .append( '3' );