How to Create a Button That Jumps Between Two Functions When Clicked in JavaScript?

Estimated read time 1 min read

You can create a button in HTML that jumps between two functions in JavaScript by using the onclick event. The onclick event is triggered when a user clicks on an element, in this case, the button.

Here’s an example of how to create a button that alternates between two functions when clicked:

<button id="myButton">Click Me</button>

  var toggle = true;
  document.getElementById("myButton").onclick = function() {
    if (toggle) {
    } else {
    toggle = !toggle;

  function function1() {
    alert("You have clicked Function 1");

  function function2() {
    alert("You have clicked Function 2");

In this example, the toggle variable is used to keep track of which function should be executed when the button is clicked. The value of toggle is flipped every time the button is clicked, and either function1 or function2 is executed accordingly.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply