Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript addEventListener function syntax

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?

like image 387
Dillinger Avatar asked Jun 04 '26 01:06

Dillinger


2 Answers

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).

like image 103
Jonathan Lam Avatar answered Jun 06 '26 14:06

Jonathan Lam


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)
like image 32
Nicola Bizzoca Avatar answered Jun 06 '26 14:06

Nicola Bizzoca