Search code examples
javascriptweb

how to make a button call different function every-time it's clicked?


How do I make a button call different function every time it's clicked?

    <button id="OpenGoogle">
        Open Google, facebook, instagram
    </button>

I have 3 functions and I want call them with the same button, like that:

1st click calls func1(),

2nd click calls func2(),

3rd click calls func3(),

function func1(){
    window.open("https://www.gmail.com");
}
function func2(){
    window.open("https://www.facebook.com");
}
function func3(){
    window.open("https://www.instagram.com");
}

Solution

  • function func1(){
        console.log("goo");
    }
    
    function func2(){
        console.log("fac");
    }
    
    function func3(){
        console.log("insta");
    }
    
    const btn = document.querySelector("#OpenGoogle");
    funcs = [func1, func2, func3];
    let i = 0;
    
    btn.addEventListener("click", e => {
       funcs[i]();
       i++;
       if (i >= funcs.length) i = 0;
           
    });
    <button id="OpenGoogle">
      Open Google, facebook, instagram
    </button>