Search code examples
javascriptfunctiontoggle

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!


Solution

  • You have to use a variable to manage the toggle:

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