Eric Hamm Eric Hamm - 10 months ago 30
HTML Question

Assign onclick to a function issue

my code to add a the onclick function is as follows

newbutton.onclick = whoWon(this.id)


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(this.id) will actually call the whoWon function.

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

newbutton.onclick = whoWon.bind(null, this.id)

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

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