AndreKuntze
AndreKuntze

Reputation: 163

Javascript: Code is called on load but should run when a click event happened

I am trying to understand the Javascript event handling. I like some code to be called when I press a button and added an eventlistener - my code:

<html>
 <head>
    <title>
        PDSA #4.4: Event Registering
    </title>
    <script>
        function changeTheButton(btn){
            btn.innerHTML = "Please, don't press again!";
            alert("Changed the button");
        }

        function init(){
            btn = document.getElementById("button1");
            btn.addEventListener("click", changeTheButton(btn), false);
        }
    </script>
 </head>
 <body onload="init()">
    <form>
        <button id="button1">Don't press this button</button>
    </form>
 </body>
</html>

When I open this site in Chrome or Firefox the text on the button is already "Please, don't press again!" and the alert is opened before I do anything.

Why does this happen? I expected this to happen, when I press the button and not on load.

Thanks in advance for any help André

Upvotes: 1

Views: 115

Answers (1)

Niklas B.
Niklas B.

Reputation: 95318

Watch this line:

btn.addEventListener("click", changeTheButton(btn), false);

You're actually calling changeTheButton right there, resulting in the alert. You probably want to register it as an event handler instead, thus deferring the alert until the button is pressed:

btn.addEventListener("click", function() { changeTheButton(btn) }, false);

You can watch the result at jsFiddle.

One additional problem you might experience is that the button click causes a page reload, because the default event handler is still called. You can prevent that by calling .preventDefault() on the event instance:

function changeTheButton(ev, btn) {
    alert("Changed the button");
    btn.innerHTML = "Please, don't press again!";
    ev.preventDefault();
}

function init(){
    btn = document.getElementById("button1");
    btn.addEventListener("click", function(ev) { 
        changeTheButton(ev, btn) 
    }, false);
}

Demo.

Upvotes: 2

Related Questions