addEventListener runs my function immediately instead of on click
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.
Cite
CoursesWeb 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.<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:
clickedand 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.
Write something first.
Give people something to work with: at least 30 words on what happened and what you tried.
That is too long. Keep it under 6,000 characters.
Write the question as the title, 15 to 140 characters, no links.
Pick a category.
Add a name (2 to 40 characters, no links).
That email address does not look right.
That was quick. Read the thread, then try again.
The form expired. Reload the page and post again.
Something went wrong with the form. Reload and try again.
Please complete the check and post again.
Limit reached for now. Try again later.
This thread is closed to new replies.
This thread no longer accepts replies.
Something went wrong with the form. Reload and try again.
Post a reply or question first (name and email), then this browser can vote, edit and accept answers.
You cannot vote on your own post.
Only the author (within 30 days) or the forum team can do that.
That email already has an account. Use your sign-in link instead.
New accounts are paused for the moment. Try again later.
That was already posted.
2 answers
- 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.