A micro jQuery plugin:
jQuery.fn.clickToggle = function(a,b) {
var ab = [b,a];
return this.on("click", function(){ ab[this._tog^=1].call(this); });
};
// USE LIKE:
$("button").clickToggle(function() {
console.log("AAA");
}, function() {
console.log("BBB");
}); // Chain here other jQuery methods to your selector
Taken from my answer here https://stackoverflow.com/a/21520499/383904
There's other ways to toggle a state / value:
LIVE DEMO
var editAdd = [editList, addList], // store your function names into array
c = 0; // toggle counter
function editList(){ // define function
alert('EDIT');
}
function addList(){ // define function
alert('ADD');
}
$('#edit a').click(function(e){
e.preventDefault();
editAdd[c++%2](); // toggle array index and use as function
// % = Modulo operator
});
where instead of the modulo operator %
you can use the
Bitwise XOR operator ^
like: [c^=1]
Using Array.reverse()
LIVE DEMO
var editAdd = [editList, addList];
function editList(){
alert('EDIT');
}
function addList(){
alert('ADD');
}
$('#edit a').click(function(e){
e.preventDefault();
editAdd.reverse()[0]();
});
reverse will invert our array on every click, all we need to do is take the 0 indexed value [0]
and run that function name [0]()
.