I'm trying to make a toggle function, so when you click a link it does one thing and when you click the same link again it does another thing. My problem comes is that I'm using the latest version of Jquery and it seems that toggle-event is Deprecated.
I was trying to work with this before I found it was deprecated.
$('#edit a').toggle(
function(){
editList();
},
function(){
addList();
});
It says in the docs that it's already binded to click.
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]()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With