Monday, October 27, 2008

jQuery If, ElseIf, and Else plugin

Update
Guys, I have to admit I created silly prototypes while all I need were much more simpler than I though :) Enjoy last version!
-------------------------------------

Try to imagine a page like this one:

<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</body>


.. and now try to imagine something like this:

function oddNumbers(){
// return true if element contain an odd number
return $(this).text() & 1;
};

$(function(){
$("div")
.If(function(){return $(this).text() == "3" || $(this).text() == "5"})
.text("match the 3 or 5 check")
.ElseIf(oddNumbers)
.text("odd numbers")
.ElseIf(function(){return $(this).text() == 2})
.Do(function(){ // if you need a closure ...
$(this).text("text is equal 2");
})
.ElseIf(function(){return $(this).text() == 6})
.text("match the 6 condition")
.Else()
.text("this is 4 or 8");
;
})


... now, try to imagine I created a plugin like this:


;jQuery.fn.extend({
// Andrea Giammarchi - Mit Style Licence - V0.1f
If:function(fn){
var $ = this.filter(fn);
$.__If__ = this.filter(function(){return !~$.index(this)});
return $;
},
ElseIf:function(fn){
var $ = this.__If__.filter(fn);
$.__If__ = this.__If__.filter(function(){return !~$.index(this)});
return $;
},
Else:function(){
return this.__If__;
},
Do:jQuery.fn.each
});


... and now try to enjoy it :D

Kind Regards

No comments:

Post a Comment