Skip to content
CoursesWeb Forum

addEventListener runs my function immediately instead of on click

Asked by Kaveh S. · JavaScript and the DOM2 repliesupdated

Short answer

ok this is driving me crazy. my function runs the moment the page loads and then clicking the button does nothing at all. console.log shows "clicked" before I even touch anything.

Written by Kaveh S. ·
CiteCoursesWeb Forum, "addEventListener runs my function immediately instead of on click", https://coursesweb.net/forum/t/addeventlistener-runs-my-function-immediately-instead-of-on-click/, accessed 2026-12-03.
  1. Member ·
    <button id="buy">Add to cart</button>
    <script src="app.js"></script>
    
    const btn = document.querySelector("#buy");
    
    function showMessage() {
      console.log("clicked");
    }
    
    btn.addEventListener("click", showMessage());
    

    Console on page load:

    clicked
    

    and after that, nothing, however many times I click the button. No red errors either.

    I added console.log everywhere to check. The function is found, the button is found. In my bootcamp the instructor wrote the same line with the same brackets, I think. So why does it fire early? I do not just want a fix, I would like to understand why a function that I "gave" to the button gets run by the page.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

  1. Mpho N.Member ·

    The browser needs to know it is a call, so put it in quotes: btn.addEventListener("click", "showMessage()"). That is how onclick="showMessage()" works in HTML, same idea. In HTML the browser reads the text and makes the function for you, so I think addEventListener should accept the text too.

  2. Gaelle R.Member ·

    I think the brackets are the problem. showMessage() means "run it now". Try showMessage without brackets, so just the name of the function. I had the same problem in my first CSS animation project, but with JavaScript.

CoursesWeb Forum. Questions and answers on learning web development: HTML, CSS, JavaScript, PHP, MySQL, Node.js and AI coding help.