difference between alert(“Hi!”) and function(){alert(“Hi!”)} [duplicate]


When we are doing inline command in the button:

<button id="myButton" onclick="alert('Hi!')"> 

Why does

document.getElementById("myButton").onclick = alert('Hi!') 

not work but give the alert as the page is loaded? I can't understand how it works with function() added to it and without function(). I hope you guys understand my question. I'm missing something here.


Answers:


document.getElementById("myButton").onclick = alert('Hi!')

is wrong since onclick should be assigned to a function reference, not the function call result itself.

It will execute alert('Hi!') when the page is loaded but that is not the intention here, is it? The intention behind assigning an onclick handler is to ensure that when the button is clicked this alert will be executed.

For that to happen it should be:

document.getElementById("myButton").onclick = function(){alert('Hi!')};

Also, this will not work unless it is wrapped inside the window.onload event:

window.onload = function(){
    document.getElementById("myButton").onclick = function(){alert('Hi!')};
};