Ramya S
Ramya S

Reputation: 3094

How to toggle between two different functions when a button is clicked using javascript?

On click of a button i'm calling this function

toggleFunction(){
    //Do something here to toggle between function A and function B
}

A(){} //Call this first
B(){} //Call this after

How can i implement in javascript in a simple way?

Thanks a lot in advance!

Upvotes: 0

Views: 1408

Answers (3)

Faly
Faly

Reputation: 13356

You have to use a variable to manage the toggle:

var toggle = true;

function toggleFunction(){
    toggle ? functionA() : functionB();
    toggle = !toggle;
}

functionA() {}
functionB() {}

Upvotes: 4

deEr.
deEr.

Reputation: 557

As @Faly says, you need a variable to toggle.

New way is to cast a boolean to a number with ~~.

function A() {console.log('A');
function B() {console.log('B');
var funcs = [A,B]; 
var bool = false; 
function toggleFunction() { 
  funcs[~~bool](); 
  bool = !bool; 
}

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

Set a lastInvokedIndex property that will save the last invoked method name

btn.addEventListener( "click", function(e){
  var methodsToInvoke = [ A, B ];
  var el = e.currentTarget;
  //el.lastInvokedIndex = el.lastInvokedIndex || 0;
  el.lastInvokedIndex = el.lastInvokedIndex >= methodsToInvoke.length ? 0 : (el.lastInvokedIndex || 0);
  methodsToInvoke[el.lastInvokedIndex++]();
});

Demo

var A = () => { console.log("A") };
var B = () => { console.log("B") };

var btn = document.querySelector( "button" );

btn.addEventListener( "click", function(e){
  var methodsToInvoke = [ A, B ];
  var el = e.currentTarget;
  //el.lastInvokedIndex = el.lastInvokedIndex || 0;
  el.lastInvokedIndex = el.lastInvokedIndex >= methodsToInvoke.length ? 0 : (el.lastInvokedIndex || 0);
  methodsToInvoke[el.lastInvokedIndex++]();
});
<button>Click</button>

Upvotes: 0

Related Questions