0

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!

0

3 Answers 3

4

You have to use a variable to manage the toggle:

var toggle = true;

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

functionA() {}
functionB() {}
Sign up to request clarification or add additional context in comments.

Comments

1

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; 
}

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.