Basically, when a button is pressed I want an argument to be supplied with it but this does not work:
var button = document.getElementById("button");
button.onClick = doThis(arg);
but this does work (without arguments):
var button = document.getElementById("button");
button.onClick = doThis;
The reason why the first example doesn't work it because the function automatically runs without waiting for the click.
How do I supply arguments onClick?
Basically, when a button is pressed I want an argument to be supplied with it but this does not work:
var button = document.getElementById("button");
button.onClick = doThis(arg);
but this does work (without arguments):
var button = document.getElementById("button");
button.onClick = doThis;
The reason why the first example doesn't work it because the function automatically runs without waiting for the click.
How do I supply arguments onClick?
Share Improve this question asked Nov 3, 2015 at 7:32 mre12345mre12345 1,1274 gold badges16 silver badges24 bronze badges 03 Answers
Reset to default 6First, note that it's onclick
, not onClick
. Both work on major browsers, but the former is the correct capitalization. (See here and here in the HTML specification, including the code example.)
You have a couple of choices:
Use
Function#bind
:button.onclick = doThis.bind(button, arg);
Function#bind
creates a new function that, when called, will call the original with a specificthis
value (the first argument,button
in our case) and any arguments you give it (followed by any arguments the new function is called with).Use a wraper function:
button.onclick = function() { doThis(arg); };
within the above, though,
this
indoThis
will not be the button. If you want it to be, you can useFunction#call
:button.onclick = function() { doThis.call(button, arg); }; // or button.onclick = function() { doThis.call(this, arg); };
Function#call
calls a function, specifying thethis
value to use, along with the arguments to pass to it.
You could do it like this using an anonymous function.
document.getElementById("button").onClick = function() { doThis(arg); };
You can do it well using addEventListener
in JavaScript
.
HTML5
data
-attributes and DOMStringMap
can be utilized to extend it further.
Below code snippet should give you fair idea of using arguments with any HTMLDomEvents
.
el.addEventListener('click', function(e) {
performAction(e, this);
});
var elContainer = document.querySelector('#myDiv');
var el = document.querySelector('#searchNow');
el.addEventListener('click', function(e) {
performAction(e, this);
});
function performAction(e, thatObj) {
var str = '' + e.type + '\n';
for (x in thatObj.dataset) {
str += x + ': ' + thatObj.dataset[x] + '\n';
}
console.log(e.type + thatObj.dataset);
elContainer.innerHTML += str;
}
#myDiv {
margin: 5px 0;
padding: 5px;
border: 1px solid #CCC;
}
<div id="myDiv">
My DIV...
<br/>
</div>
<button name='search' id='searchNow' data-propertiesObject='{a: "XYZ", b: "ABC"}'>Search Now!</button>