addEventListener "click" - starts on page load

826 Views Asked by At

I can't understand, why addEventListener("click") starts after page loading, not waiting for "click". What is worse - it does not work on click again. Below you can find script:


const seven = document.getElementById("seven");
seven.addEventListener("click", typeNumber(7));
function typeNumber(a){
    calculations.innerText = calculations.innerText + a;
    
}

No matter what function I add to event listener (console log, alert etc) it always starts when the page starts. Are you able to help?

I tried to choose different types of function invocations

2

There are 2 best solutions below

0
Unmitigated On BEST ANSWER

Call typeNumber inside an anonymous function, rather than calling it immediately and passing the return value to addEventListener (when it expects a function as the second argument).

const seven = document.getElementById("seven");
seven.addEventListener("click", () => typeNumber(7));
function typeNumber(a){
    document.getElementById("calculations").innerText = calculations.innerText + a;
}
<button id="seven">7</button>
<p id="calculations"></p>

0
Milad khajavi On

you are invoking the typeNumber function immediately when you add it as a callback to the event listener, rather than passing a reference to the function. This means that the function is executed immediately, rather than waiting for the event to occur.

you need to pass a reference to the function instead of invoking it:

const seven = document.getElementById("seven");
 seven.addEventListener("click", function() {
   typeNumber(7);
});


function typeNumber(a){
    calculations.innerText = calculations.innerText + a;
}

the typeNumber function will only be executed when the click event occurs on the seven element.