-1

How can I pass a variable to the onclick function? When using

var number = 123;
document.getElementById('myButton').onclick = myFunction(number);

It will run that function before even clicking the button because the function will be called and the return value will be put into the onclick, which doesnt help me

Without the "()" it will only call the function once I click the button, but how do I pass a variable then ?

var number = 123;
document.getElementById('myButton').onclick = myFunction;

function myFunction(i) {
    i += 10;
    alert(i);
}
SomeCoder
  • 275
  • 1
  • 19
  • `myFunction.bind(null, number)` or `function(){myFunction(number)}`. – Lain Feb 15 '20 at 11:55
  • Or the arrow function equivalent `document.getElementById('myButton').onclick = () => myFunction(number)` – Jacob Feb 15 '20 at 11:57

1 Answers1

-1

One option would be to make the onclick an anonymous function to call myFunction.

var number = 123;
document.getElementById('myButton').onclick = () => {
  myFunction(number)
}

function myFunction(i) {
  i += 10;
  alert(i);
}
<buton id="myButton"> Test button </buton>
Jacob
  • 887
  • 1
  • 8
  • 17