Reputation: 4042
Previously, I had this line in my HTML file:
<input type="button" value="1" name="btn1" id="btn1" onclick="showNum(1)" />
This works fine, but I don't want to include the method name in the HTML file. I would like to have something like this in the HTML:
<input type="button" value="1" name="btn1" id="btn1" />
And then I want to bind this button to the method in the JS file. I tried this code and it doesn't work:
window.onload = function() {
document.getElementById("btn1").onclick = showNum(1);
};
How can I bind btn1
to run showNum(1)
using JavaScript?
Upvotes: 1
Views: 288
Reputation: 16184
It is also possible to bind a reference to the function, like so:
var showNum = function(){
alert(this.value);
}
window.onload = function() {
document.getElementById("btn1").onclick = showNum;
};
<input type="button" value="1" id="btn1" />
Upvotes: 2
Reputation: 532
I can't tell you exactly why it works like this, but if you use an anonymous function with showNum(1);
inside of it when assigning to onclick, it works fine.
window.onload = function() {
document.getElementById("btn1").onclick = function () {
showNum(1);
}
};
Also a tip, window.onload
can only be used once, so if you have a master page in your site that also needs to run a script when the page starts, it can be overridden. Use a self-starting function like this and then you won't have to worry about that, and you can have as many as you want. Plus it's cleaner and looks nicer (at least to me).
(function () {
document.getElementById("btn1").onclick = function () {
showNum(1);
}
})();
Just make sure it's after the rest of your JS code and HTML, since pages load from the top down.
Upvotes: 1
Reputation: 2926
showNum
instead of showNum(1)
showNum
- is handler, but showNum(1)
- is result of the execution.
if parameter is required: showNum.bind(this, 1)
;
Or even better - addEventListener
can be used:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Upvotes: 0
Reputation: 311
window.onload = function() {
document.getElementById("btn1").addEventListener('click', ()=>showNum(1));
};
Upvotes: 0
Reputation: 781130
You need to create a new function that calls showNum()
with the argument you want.
window.onload = function() {
document.getElementById("btn1").onclick = function() {showNum(1);};
};
You can also use the .bind()
method to bind the argument.
window.onload = function() {
document.getElementById("btn1").onclick = showNum.bind(null, 1);
};
Upvotes: 1