1

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

        }

2 Answers 2

0

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.

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.