Reputation: 407
How can I add an eventlistener to my button? When the button is clicked the function speler1gooien has to run. When I run my example code below the function speler1gooien is fired on page load. What is the correct way to run my function only when clicked?
window.onload = function () {
buttonSpeler1 = document.getElementById("buttonspeler1");
buttonSpeler2 = document.getElementById("buttonspeler2");
tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
resultaat = document.getElementById("resultaat");
buttonSpeler1.addEventListener("click", speler1gooien());
};
var speler1gooien = function() {
// some code
}
Upvotes: 1
Views: 914
Reputation: 64526
Remove the parenthesis in the call speler1gooien()
because it's causing your function to be executed immediately, and the return value is being passed as the click event handler.
buttonSpeler1.addEventListener("click", speler1gooien);
// ^ removed ()
By removing the parenthesis, you are passing the function object, instead of executing it.
Upvotes: 0
Reputation: 422
You are trying to attach function speler1gooien as onclick handler, but your code attaches as handler the result of spele1gooien function. Just remove ()
following name of that function
window.onload = function () {
buttonSpeler1 = document.getElementById("buttonspeler1");
buttonSpeler2 = document.getElementById("buttonspeler2");
tafelp2.src = "images/rechts_" + aantalBekersP2 + ".png";
resultaat = document.getElementById("resultaat");
buttonSpeler1.addEventListener("click", speler1gooien);
};
var speler1gooien = function() {
// some code
}
Upvotes: 0