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){
  }
}
0

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.