My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Tuesday, October 28, 2008

jQuery plug-in distributed elements via If, ElseIf, and Else

After a couple of instant and consecutive releases, I ended up with a plug-in that fits minified into 240 bytes :)

Here is the official plug-in page, while this is the example page and this is the summary:

// Andrea Giammarchi - Mit Style Licence - V0.2
var __If__ = this.__If__ || this,
$ = __If__.filter(fn);
$.__If__ = __If__.filter(function(){return !~$.index(this)});
return $;
return this.__If__;
}); jQuery.fn.ElseIf = jQuery.fn.If;

1 comment:

Anonymous said...


Based largely on your code I've added basic tree handling by adding an EndIf function that restores the previous selection.
Code style is a bit different from yours, but the added bits should be clear.

(function( $ ){
$.fn.IF = function(f) {
var s = this.filter(f);
s.__BEFORE = this;
s.__ELSE = this.filter(function(){return !~s.index(this)});
return s;

$.fn.ELSEIF = function(f) {
var e = this.__ELSE;
var s = e.filter(f);
s.__BEFORE = this.__BEFORE;
s.__ELSE = e.filter(function(){return !~e.index(this)});
return s;

$.fn.ELSE = function() {
var s = this.__ELSE;
s.__BEFORE = this.__BEFORE;
return s;

$.fn.ENDIF = function() {
return this.__BEFORE;