Eric Hamm Eric Hamm -3 years ago 82
HTML Question

Assign onclick to a function issue

my code to add a the onclick function is as follows

newbutton.onclick = whoWon(

Other Relevant Code

var winner;

function whoWon(name){
winner = name

My problem is that the onclick when i try to assign it executes and doesn't add the onclick. I know this because when I create the new button the variable winner is always the most recent button created. Also when I inspect the element in google chrome the only thing that is assigned is the ID and the Class.

Answer Source

newbutton.onclick = whoWon( will actually call the whoWon function.

You need to pass the whoWon as is, without calling it and bind it the This should do the trick:

newbutton.onclick = whoWon.bind(null,

Or as mentioned by @styfle in the comments, you could create an anonymous function:

newbutton.onclick = () => whoWon(
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download