I am trying to pass a function Which has 2 arguments to the addEventListener method on specific button but the problem is function executing directly when page loading instead of executing it when some one clicked the button.
I know how to make it work with anonymous function but I need it to work with a specific defined function instead.
function changeContent(elem,str){
elem.textContent = str;
}
var btn = document.querySelector("button");
var p = document.querySelector("p");
var content = "Someone Clicked the Button!";
// add event listener on click to the button
// version 1 with anonymous function worked as expected
btn.addEventListener("click",function(){
p.textContent = content;
});
// version 2 with specific defined function not working as expected
btn.addEventListener("click",changeContent(p,content));
any idea of the reason why second version isn't working and how to make it work as expected.
Update:
my intended and important question:
is there any way to make
changeContent(p,content)function work without wrap it with a (anonymous) function inaddEventListenermethod ?