Bekki
Bekki

Reputation: 729

Pass parameter to function with addEventListener

I have an anonymous function

function getStocks(item){
   alert(item);
}

Below is my click event listener.

document.getElementById("passBtn").addEventListener("click", getStocks, false);

I need to pass a parameter to getStocks(). I tried the below but does not work. What's wrong?

document.getElementById("passBtn").addEventListener('click', function(){
  getStocks(item);
}, false);

Upvotes: 1

Views: 59

Answers (1)

jonny
jonny

Reputation: 3098

Use the javascript bind function:

var item = "item";
document.getElementById("passBtn").addEventListener("click", 
    getStocks.bind(null, item), false);

See the above code in action, here: fiddle

See more information, here: Function.prototype.bind()

Upvotes: 1

Related Questions