0

How exactly is JS triggering the button's onclick function even before its been clicked during page load?

P.S:I come from PYTHON background

var btn = document.getElementById("btn")

// this works fine (alert box appears when clicked)

btn.onclick = function(){
    alert('clicked')
}

// this shows alert box when the page loads when clearly onclick is mentioned

function foo(){
    alert('clickedd')
}
btn.onclick = foo()

This is for the simple HTML button inside a form table.

  • 1
    You're calling it instead of assigning it with this `btn.onclick = foo()` it should be `btn.onclick = foo`. (technically you're assigning the return value of `foo()` in the first instance, which is `undefined`) – pilchard Apr 23 '22 at 21:12
  • 1
    the first `btn.onclick = foo()` execute the foo function and assign a undefined value to `btn.onclick` ( `foo()` return undefined ) and the second `btn.onclick = function(){ ...` re-assign a function to `btn.onclick` – Mister Jojo Apr 23 '22 at 21:16
  • it works but i want to understand if onclick is a button's method and foo()'s return value is assigned to it then how is that getting triggered without the button being clicked? – Subasish Ghosh Apr 23 '22 at 21:19
  • 1
    You are literally calling the function before assigning it's return value to the button's onclick. `btn.onclick = foo()` is resolved right to left so it calls `foo()` which calls `alert()` and then implicitly returns `undefined` since you haven't specified a return, and this is assigned to the button's onclick property. If `foo()` returned a function that function would become the button's onclick method. `function foo() { return function () {alert('nested function')}}` – pilchard Apr 23 '22 at 21:23
  • `btn.onclick =` is a function Object assignment, not a value assignment – Mister Jojo Apr 23 '22 at 21:29

0 Answers0