3

I am having trouble understanding why the function parameter of the event listener isn't accepting just the function. Here's the code:

Variables are declared:

var spanJS = document.getElementById("spanJS")
var txtPlayers = document.getElementById("ContentPlaceHolder1_txtPlayers")
var txtAmount = document.getElementById("ContentPlaceHolder1_txtAmount")

Then associate the event listeners:

txtAmount.addEventListener("keyup", UpdateTotals())
txtPlayers.addEventListener("keyup", UpdateTotals())

Then the function:

function UpdateTotals() {
      ... 
}

This is the whole code. The problem is, when i run it, it executes UpdateTotals() without any keyup event, and the listeners don't work.

If i do the following change, it works like intended:

txtAmount.addEventListener("keyup", function () {
UpdateTotals()
})
txtPlayers.addEventListener("keyup", function () {
UpdateTotals()
})

Can anyone explain me why i can't just put the function's name, i have to "child" it in another function?

Dillinger
  • 341
  • 3
  • 16
  • Does this answer your question? [addEventListener calls the function without me even asking it to](https://stackoverflow.com/questions/16310423/addeventlistener-calls-the-function-without-me-even-asking-it-to) – ggorlen Feb 16 '21 at 20:40

3 Answers3

5

You need to change the event listeners by removing the () at the end of the handler names, like so:

txtAmount.addEventListener("keyup", UpdateTotals);

This is to pass the reference of the function UpdateTotals, and not run the function UpdateTotals(). The latter will actually run the function immediately, and pass in the return value of the function.

See this link about the idea of JavaScript function references (without parentheses).

Community
  • 1
  • 1
Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
3

In Javascript, UpdateTotals() is the value of the function when called without passing arguments, while UpdateTotals is the function itself

So you want:

txtAmount.addEventListener("keyup", UpdateTotals)
txtPlayers.addEventListener("keyup", UpdateTotals)
Nicola Bizzoca
  • 1,125
  • 8
  • 7
2

You don't need the parentheses within the event listeners.

Change:

txtAmount.addEventListener("keyup", UpdateTotals())
txtPlayers.addEventListener("keyup", UpdateTotals())

to:

txtAmount.addEventListener("keyup", UpdateTotals)
txtPlayers.addEventListener("keyup", UpdateTotals)
Galen Cook
  • 124
  • 2