However, in certain scenarios when passing something through a parameter, the approach would be:
var foo = document.getElementById("foo");
foo.addEventListener("keydown", foo("Hello, world!"));
function foo(e){
console.log(e);
}
Actually, that is incorrect. By doing this, you would immediately invoke `foo` with its argument, resulting in the return value (which, in your case, is `undefined`) becoming the callback reference for the `keydown` event, and `undefined` cannot be a callback reference.
Let's see this in action. Below, 'Hello, world!' gets printed to the console right away, and nothing happens when a key is pressed down in the input field:
var input = document.getElementById("input");
input.addEventListener("keydown", foo("Hello, world!"));
function foo(e){
console.log(e); // Printed to console immediately!
}
<input id="input">
The second parameter for .addEventListener()
requires a function reference, which can be provided in various ways:
Pass the name of the function (without parenthesis):
.addEventListener("click", foo);
Provide an anonymous function (just pass the function without invoking it):
.addEventListener("click", function(){ /* function body */ });
Include code that returns a function as the callback reference (note the parenthesis here) where `foo` is invoked first and the returned value, which should be a function, acts as the callback reference:
function foo(){
return function(){ console.log("Hello, world!"); };
}
.addEventListener("click", foo()); // foo is called first
However, if `foo` needs to be the function reference AND it requires arguments, including parentheses will invoke the function immediately. Therefore, you must wrap the function call in an anonymous function, as shown previously:
function foo(e){
console.log(e);
}
var input = document.getElementById("input");
// The anonymous function serves as the reference to execute when
// the event occurs. It will then call foo with the necessary arguments.
input.addEventListener("keydown", function(){ foo("Hello, world!"); });
<input id="input">