Oghli
Oghli

Reputation: 2340

Passing function with 2 arguments to addEvent Listener method

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 in addEventListener method ?

Upvotes: 1

Views: 219

Answers (1)

Julian
Julian

Reputation: 36710

Wrap it also in an anonymous function

btn.addEventListener("click",function() { 
    changeContent(p, content)
});

any idea of the reason why second version isn't working

Because changeContent is intermediate called because you're passing arguments to it (with the round brackets). In general you could pass a function to a function in two ways:

  1. Only the name, e.g. passFunction(changeContent);
  2. Wrap in a (anonymous) function, as shown above passFunction(function() { changeContent( ...);} );. The anonymous function isn't called intermediately, because you aren't passing parameters to it.

can you explain this point changeContent is intermediate called

If you pass arguments to a function, it's called. If you wrap it in an (anonymous) function, without passing arguments to the (anonymous) function, the (anonymous) function isn't called and hence also not the wrapped function.

is there any way to make it work without wrap it with a (anonymous) function

Use the .bind function. The first argument is the value of this. So you need 3 parameters for this case:

btn.addEventListener("click",changeContent.bind(this, p, content));

For more info, see the docs of .bind

Upvotes: 3

Related Questions