3

I want to pass an argument to the function that is being called inside of the event listener. The code below shows what I want to do however it is not letting me do it conventionally. What is a workaround to this?

HTML code :

<button id='btn'>Click Me</button>

JavaScript code :

<script>
document.getElementById('btn').addEventListener( "click",btnClick(5) );
function btnClick(argument)
{
console.log("Button clicked with argument : " + argument);
}
</script>

Console should read :

Button clicked with argument : 5

Thanks guys.

user3677286
  • 125
  • 2
  • 9

1 Answers1

4

With an anonymous function

document.getElementById('btn').addEventListener( "click", function() {
    btnClick(5);
}, false );

If you need to keep the value of this you can use call or apply

btnClick.call(this, 5);
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    Why do you keep answering those questions? ;) http://stackoverflow.com/q/23548403/218196, http://stackoverflow.com/q/23005695/218196 – Felix Kling Aug 21 '14 at 19:46
  • @FelixKling - Yeah, I noticed the dupe. I have no idea, I just sometimes answer without thinking, other times I instantly remember a dupe and tag etc. Depends ! – adeneo Aug 21 '14 at 19:48
  • @FelixKling - Maybe I can blame dementia ? – adeneo Aug 21 '14 at 19:52