Skip to content
Advertisement

Event listener does not work with pre-defined function as parameter

I’m a beginner and I have just tried to do this:

ul.addEventListener("click", function(e) {
  console.log("Hi");
});

This works. I understand that this is an anonymous function. However, when I try to give a definition of this function beforehand and pass it in like so, it won’t work:

function myFunc(e) {
  console.log("Hi from myFunc");
}

ul.addEventListener("click", myFunc(e));

I do not understand what the difference is. The error reads:

Uncaught ReferenceError: e is not defined
at javascript.js:29

Advertisement

Answer

Pass the reference of the function, not the result of it’s execution. It will call your function when click event will be fired. It is the same as you pass through an anonymous function, in 2 cases you pass only the reference of the function.

function myFunc(e) {
  console.log("Hi from myFunc");
}

ul.addEventListener("click", myFunc);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement