I'm still learning the basics of JavaScript, I'm learning about events right now and I ran into a doubt:
Why does the onclick function must be declared in assignation?
I have this code for a counter that goes up when you click a button:
let button1 = document.getElementById("button1");
button1.onclick=function add1(){
let input1 = document.getElementById("input1");
input1.value = parseInt(input1.value) + 1;
}
this code works correctly, however if I tried to refactor the code like this:
function add1(){
let input1 = document.getElementById("input1");
input1.value = parseInt(input1.value) + 1;
}
let button1 = document.getElementById("button1");
button1.onclick = add1();
it doesn't. the function executes itself only once on page load rather than onclick.
I wanted to know what's the difference here?
To make it work, remove the ()
where you're doing the assignment, since that's the operator that invokes a function.
button1.onclick = add1; // No parentheses
Now you're performing an assignment of the function object to the .onclick
property, so that the browser's internal event system can invoke the function when an appropriate event takes place.