Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Between 2 Functions [duplicate]

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.

like image 369
Howdy_McGee Avatar asked Dec 06 '22 08:12

Howdy_McGee


1 Answers

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]().

like image 150
Roko C. Buljan Avatar answered Dec 22 '22 00:12

Roko C. Buljan