James McClain
James McClain

Reputation: 11

How to toggle between functions on button click

I have a button that I want to switch between 2 different functions when clicked. like first click would call function A, second click would call function B, Third Click would call function A etc.

for html I have something like this:

<input type="image"onclick="test()">

for javascript I have:

<script>
val = 1;
function test () {

    if (val = 1 ) {
    function1 ();
}
    else {
    function2 ();}
}
</script>

<script>
function function1() {
alert("1");
val = 2;}
</script>

<script>
function function2() {
alert("2");
val = 1;}
</script>

it only ever runs function1 Even if I set val = 2 it will run function1. any idea what im doing wrong?

Upvotes: 1

Views: 130

Answers (2)

John
John

Reputation: 3545

If you need only toggle button, you can try XOR style function.

<script>
    val = 0;
    function toggle(){
        val = val ^ 1; // XOR 0^1 => 1, 1^1 => 0
        if(val == 0){
          //do something
        }else{
          //do something else
        }
    }
</script>

OR in shorter way

<script>
    val = 0;
    function toggle(){
        val = val ^ 1; // XOR 0^1 => 1, 1^1 => 0
        val == 0 ? function1(): function2();
    }
</script>

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

You were using the assignment operator to check the value. Use the equality operator instead:

<script>
val = 1;
function test () {
    if (val == 1 ) {  // compare values using == (or maybe ===)
        function1();
        val = 2;      // use the assignment operator here
    }
    else {
        function2();
        val = 1;
    }
}
</script>

Update:

As @nnnnnn pointed out, you might want to update your toggle state inside test() directly.

Upvotes: 2

Related Questions