Skip to content Skip to sidebar Skip to footer

Why Is Listner Function Running Without The Click Event?

(A note to the moderators - a similar question has been answered here stackoverflow link. Although the problem was solved, a proper explanation was missing regarding what was causi

Solution 1:

When you use parenthis after a function reference like so functionName() you're telling JS to call the function with the name functionName. So, in your case, you are calling listnerFunction() when you add your event listener:

// --------------------------------\/\/\/\/\/\/\/\/ -- executes listnerFunction()
inkVar.addEventListener("click", listnerFunction("Case 2"));

Thus, this really evaluates to:

inkVar.addEventListener("click", undefined);

As listnerFunction("Case 2") returns undefined (as nothing is returned from it)

In order to do what you're after you can wrap your function call in its own (anonymous) function, such that the (anonymous) function can execute your function call which is then able to pass through your desired argument:

inkVar.addEventListener("click", function() {
  listnerFunction("Case 2");
});

Solution 2:

When you are doing this:

    linkVar.addEventListener("click", listnerFunction("Case 2"));

you are passing the result of calling listnerFunction("Case 2") to addEventListener not the function itself as you do in the first case.

What you'll want to do is this:

    linkVar.addEventListener("click", () =>listnerFunction("Case 2"));

Post a Comment for "Why Is Listner Function Running Without The Click Event?"