I have a question

javascript how to attach two functions to the button so after clicking at the first time runs first function and after 2nd runs 2nd function and at 3rd first again and at fourth 4th and so on?

I wonder if you could change the function assigned to the button within the functions… so in the first_click function, button.onclick=second_function… then in the second_click function, reassign button.onclick back to the first_function.

You can accomplish what you want to do with a single function. Here’s how I would do it: Track the number of clicks in a global variable specific to that button, let’s say let buttonClicks = 0 for the time being. Every time the button is clicked, you check whether that index exists in the function container, and if so, execute that function, and then the counter increases.

In the example below, I created an object to house static references to functions embedded directly in the object you could just as easily set each index to the name of a function you create like so:

function someFunction () {
    console.log('something');
}

const myFunctions = {
    0: someFunction
}

Here’s a JS fiddle that I made to illustrate this: JS Fiddle

1 Like

@marcusparsons That is not what the user asked for. The user wants the first function to run on the 1st, 3rd, 5th, 7th… and the second function to run on the 2nd, 4th, 6th, 8th… Bascially, the same function will run ever other time the button is clicked.

@lolek55507 I think one of the easiest ways to what you want would be to define both functions and do something similar to what @kinome79 suggested above.

Oh shoot I did read it wrong. Thanks.

To attach two functions to a button in JavaScript and alternate their execution on each click, you can use a variable to keep track of the current function to execute. Here’s an example code snippet:

// define the functions to be executed
function firstFunction() {
  console.log("First function executed");
}

function secondFunction() {
  console.log("Second function executed");
}

// initialize the counter to keep track of which function to execute next
let counter = 1;

// add event listener to the button
const button = document.querySelector("#myButton");
button.addEventListener("click", function() {
  if (counter % 2 !== 0) {
    firstFunction();
  } else {
    secondFunction();
  }
  counter++;
});


In this example, the counter variable is initialized to 1. On each click of the button, the counter is incremented by 1. If the counter is odd, the firstFunction() is executed, otherwise, the secondFunction() is executed.

This code will alternate between the two functions every time the button is clicked.
I have learnt about function for click button from a enablegeek.