Why the onclick handler fires when the page loads?

Hello, is the code:
var someBtn = document.getElementById('all');

someBtn.onclick = myFunction(5);

function myFunction (a){
alert(a);
}


The problem is that the function is called when the page is loaded, not when clicked. What is the matter? Thanks in advance for the answer.
June 10th 19 at 15:29
3 answers
June 10th 19 at 15:31
Solution
Because you pass in a handler not a function, and the result of its execution.
Right – so:
var someBtn = document.getElementById('all');

someBtn.onclick = function() {
myFunction(5);
};

function myFunction (a){
alert(a);
}


Or rather – here it is:
var someBtn = document.getElementById('all');

// We hang up the handler like this:
someBtn.addEventListener('click', myFunction.bind(this, 5));

// OR:
someBtn.addEventListener('click', function() {
myFunction(5);
});

function myFunction (a){
alert(a);
}
June 10th 19 at 15:33
Solution
Because you are calling the function myFunction with an argument of 5 and assign someBtn.onclick execution result and not the function itself.

Correct way:
var someBtn = document.getElementById('all');

someBtn.onclick = function() {
myFunction(5);
}

function myFunction(a){
alert(a);
}


or this:
var someBtn = document.getElementById('all');

someBtn.onclick = function() {
alert(5);
}


but in a good way:
var someBtn = document.getElementById('all');

someBtn.addEventListener('click', function() {
myFunction(5);
});

function myFunction(a){
alert(a);
}
June 10th 19 at 15:35
Need events to hang using addEventListener

var someBtn = document.getElementById('all');

someBtn.addEventListener('click', funtion(){ myFunction(5); });

function myFunction (a){
alert(a);
}
So, too, will not work, because the addEventListener in your example again passed a function, and the result of its execution - Alysson_Gaylord commented on June 10th 19 at 15:38
corrected - peter.Armstro commented on June 10th 19 at 15:41

Find more questions by tags JavaScript