Jonathan Reiser
Jonathan Reiser

Reputation: 45

How do I pass an argument to referenced function without invoking it using Javascript

I want my code to be something like el.onclick = someFunc(arg), however, someFunc is invoked on load. How would I go about passing an argument to a function that I want to reference, without also invoking it?

Upvotes: 1

Views: 64

Answers (2)

Aruna
Aruna

Reputation: 12022

You can do this in following 3 ways,

  1. Using addEventListener

var elm = document.getElementById('testButton');

elm.addEventListener('click', function(){
    someFunc('testArg');
});

function someFunc(arg) {
  console.log(arg);
}
<input id="testButton" type="button" value="Click"  />

  1. Using onclick and bind

function someFunc(arg) {
   console.log(arg);
}

var elm = document.getElementById('testButton');
elm.onclick = someFunc.bind(null, 'testArg');
<input id="testButton" type="button" value="Click" />

  1. Using onclick and function wrapper,

function someFunc(arg) {
  return function() {
    console.log(arg);
  }
}

var elm = document.getElementById('testButton');
elm.onclick = someFunc('testArg');
<input id="testButton" type="button" value="Click"  />

Note: Option 1 with addEventListener is the best one to use among the options above but other options (1 & 2) can be considered in case of option 1 is not doable.

For an instance, you can use onclick and bind when you need to reuse the same method for multiple elements and have to use the element inside the method with this as below.

var buttons = document.getElementsByTagName('input');
for(var i = 0; i < buttons.length; i++) {
   var button = buttons[i];
   button.onclick = someFunc.bind(button, 'testArg');
}

// Assume this function is in another file
function someFunc(arg) {
   console.log(this.id + ': '+ arg);
}
<div>
  <input id="testButton1" type="button" value="Click" />
  <input id="testButton2" type="button" value="Click" />
  <input id="testButton3" type="button" value="Click" />
  <input id="testButton4" type="button" value="Click" />
  <input id="testButton5" type="button" value="Click" />
</div>

Upvotes: 1

Abhinav Galodha
Abhinav Galodha

Reputation: 9878

Try using the addEventListener to add the event click. The addEventListener method attaches an event handler to the specified element. You need to pass the callback, which would be invoked when the event occurs.

movieElement.addEventListener("click", function(){
    showDescription(arg);
});

Upvotes: 2

Related Questions