(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 causing the problem)
The Problem -
Below is simple code. which displays an alert when link is clicked.
const linkVar = document.getElementById("theLink");
linkVar.addEventListener("click", listnerFunction);
function listnerFunction() {
alert("case 1");
}
<a id="theLink" href="#">click here to call the listner function</a>
Next, a small change is made, I would like to pass the alert text when call to function is made.
const linkVar = document.getElementById("theLink");
linkVar.addEventListener("click", listnerFunction("Case 2"));
function listnerFunction(passedText) {
alert(passedText);
}
<a id="theLink" href="#">click here to call the listner function</a>
This Case 2 causes the problem. Now on running the case 2 code. the alert shows without clicking and on clicking the alert doesn't show.
The Question - when an argument is passed to the listener function what really happens?