javascriptaddeventlistenerpageload

addEventListener "click" - starts on page load


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


Solution

  • 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>