Alex
Alex

Reputation: 81

addEventListener works on document load

<script>
    var clrbtn = document.createElement('button');
    clrbtn.addEventListener('click', sayHello());
    function sayHello() {
        console.log('Hello');
    }
</script>

I got Hello in console on document load, why?

Upvotes: 0

Views: 63

Answers (3)

Adrian Makowski
Adrian Makowski

Reputation: 169

Try passing to addeventlistener just name of the function you want execute on click event. Currently you have brackets there that execute sayHello beforehand and try to pass to addeventlistener value of your execution (which is undefined).

In short do this:

clrbtn.addEventListener('click', sayHello)

Upvotes: 0

orabis
orabis

Reputation: 2809

The reason is because you are invoking sayHello() rather than making a reference to it; i.e. sayHello

Upvotes: 0

brk
brk

Reputation: 50291

This is because of this line sayHello() in clrbtn.addEventListener('click', sayHello())

It will immediately execute the function.

Change it to

clrbtn.addEventListener('click', sayHello)

Upvotes: 1

Related Questions