1

I was trying to create a parameterized function using JS, I started code with a window.onload=()=>{}, and the syntax for my function is function name(arg){}.

I want to call this function on a click event. so my statement goes btn.onclick=function_name(arg); . but, the function gets called as soon as the page loads, without a click. What can i do to solve this problem?

window.onload = () => {
  var btn .....

  btn.onclick = func(arg..);

  function func(arg){
  }
}
Phil
  • 157,677
  • 23
  • 242
  • 245

1 Answers1

1

btn.onclick = func(arg..); calls the function and assigns the return value to the onclick property of btn.

Attach an event listener to the button with the snippet code. You can use data- attributes to add data to the button.

document.getElementById("btn").addEventListener("click", fn);

function fn(e) {
  this.textContent = "Clicked " + this.dataset.arg;
}
<button id="btn" data-arg="arg">Click</button>
user2182349
  • 9,569
  • 3
  • 29
  • 41