Home > Back-end >  Appending button onclick function runs when appended
Appending button onclick function runs when appended

Time:06-01

When I append a button with an onclick function, that same functions runs immediately. How do I keep the onclick function and make it not run when appended? Heres the code where it gets appended:

let button=document.createElement("button");
button.innerHTML=users[i].replace("user__","").replace("=","").substring(0,users[i].replace("user__","").replace("=","").length/2);
button.onclick=removeUser(button.innerHTML);
accounts.appendChild(button);

CodePudding user response:

As per your codebase, the button.onclick needs to be asigned as a function.

But in the code it is button.onclick=removeUser(button.innerHTML), due to this line removeUser would be directly executed when creating the button.

You might have to update your code as follow:

button.onclick = () => removeUser(button.innerHTML)

This way, the removeUser is wrapped inside a function and that function is only called when user clicks on the button. Hope this helps. :)

  • Related