If ElseIf Else jQuery Statements

The Conditional jQuery Plugin provides conditional statements for use in chaining jQuery statements. This plugin makes use of jQuery's stack architecture providing native integration and use with the .end() method. This plugin differs from other If Else jQuery plugins by not making use of .filter() so the origional jQuery collection remains intact.

jQuery Plugin Methods

The Conditional plugin adds the following jQuery methods:

  • $().If()
  • $().Else()
  • $().orIfEmpty()

Examples

Simple example: If-Else
$('div')
    .If('hasClass', 'myClass')
        .css('color', 'red')
    .Else()
        .css('color', 'blue');
        

Simple example: If-ElseIf-Else

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

Simple example: If-ElseIf-Else

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

Documentation

The Conditional plugin provides If ElseIf Else conditions within the jQuery chain. These functions provide a flexible API and clean syntax.

The .If() statement

The .If() statment can accept 3 variations of arguments, with the most basic being .If(bool)

var a = 0, b = 1;
$('div')
    .If( a == b )
        .chainedMethods();
    

The second form of .If() accepts a jQuery method name (as a string) to call, an argument to pass in, and finally an optional comparison value to test against the jQuery method's return value.

So the following code:

<a id="myLink" href="#" title="Hello">Hello World</a>

var $link = $('#myLink');
if ( $link.attr('title') == 'Hello' ) {
    $link.attr('title', 'A simple title');
} else {
    $link.attr('title', 'An exciting title!');
}
    

Would be rewritten as:

$('#myLink')
    .If('attr', 'title', 'Hello')
        .attr('title', 'A simple title')
    .Else()
        .attr('title', 'An exciting title!');
    

The third form of .If() accepts a function with a return value of boolean.

$('#myLink')
    .If(function() { return 1 == 2; })
        .attr('title', 'A simple title')
    .Else()
        .attr('title', 'An exciting title!');
    

License

The Conditional jQuery Plugin is dual licensed under the MIT or GPL licenses.

Download

Conditional 1.0 Released 2009-09-07

Tested against: jQuery 1.3.2, Internet Explorer 6+, Firefox 2+, Safari 3.x, Opera 9.63

References

Below are additional plugins that are similar or offer similar functionality.

Support

For questions or feedback, contact Jonathan Sharp at Out West Media.

Custom jQuery Development

Need this plugin modified or integrated? Out West Media provides custom jQuery development services so contact Jonathan Sharp today for a free quote.