Micro jQuery plugin
If you want to create your own clickToggle jQuery method , you can do it like this:
jQuery.fn.clickToggle = function(a, b) { return this.on("click", function(ev) { [b, a][this.$_io ^= 1].call(this, ev) }) };
<button>A</button> <button>A</button> <button>A</button> <script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
Simple Toggler Features
Live demo
function a(){ console.log('a'); } function b(){ console.log('b'); } $("selector").click(function() { return (this.tog = !this.tog) ? a() : b(); });
If you want it to be even shorter (why not?), You can use the Bitwise XOR * Docs operator , for example:
Demo
return (this.tog^=1) ? a() : b();
All this.
The trick is to set the tog property for this boolean object and toggle it using negation ( tog = !tog )
and put the necessary function calls in the conditional statement ?:
In the example, OP (even with multiple elements) might look like this:
function a(el){ $(el).animate({width: 260}, 1500); } function b(el){ $(el).animate({width: 30}, 1500); } $("selector").click(function() { var el = this; return (el.t = !el.t) ? a(el) : b(el); });
ALSO: You can also store-switches like:
DEMO :
$("selector").click(function() { $(this).animate({width: (this.tog ^= 1) ? 260 : 30 }); });
but it was not an exact request from the OP, because it is looking for a way to have two separate operations/functions
Note : this will not store the current state of Toggle, but simply invert the positions of our functions in the array (it uses ...)
You just save your functions a, b inside the array, by clicking you just change the order of the array and execute the function array[1] :
Live demo
function a(){ console.log("a"); } function b(){ console.log("b"); } var ab = [a,b]; $("selector").click(function(){ ab.reverse()[1](); // Reverse and Execute! // >> "a","b","a","b"... });
SOME MASHUP!
JQuery demo
JavaScript DEMO
Create a beautiful toggleAB() function that will contain your two functions, put them in an array , and at the end of the array you simply execute the function [ 0//1 ] accordingly, depending on the tog property that was passed to the function from this link:
function toggleAB(){ var el = this; // 'this' is the "button" Element Obj reference' return [ function() { console.log("b"); }, function() { console.log("a"); } ][el.tog^=1](); } $("selector").click( toggleAB );