1

What parameters get passed to a DOM onclick handler? How are the parameters resolved/what is the execution context of a DOM onclick handler?

See this jsbin (use the browser dev console as the jsbin one isn't very good) or the code below:

<!-- Remove the id="someid" and see what happpens -->
<input type="text" id="someid" onclick="clickHandler(this,event,someid)'"/>

<script>
   function clickHandler() {
      console.log(arugments);
   }
</script>

References

MDN DOM on-event handlers

Additional Details

I realize that attaching events in the DOM is not recommended. But this technique is still used on legacy applications and I cannot find any documentation that goes beyond passing a handler the 'this' parameter.

ksrb
  • 1,797
  • 12
  • 22
  • 3
    So what are you asking here? The arguments that are in the inline event handler is clearly passed, and seeing as it's just a function, you can pass whatever you want. Are you just confused as to why `someid` would point to the element, if so, it's because any element with an ID is added to the global `window.someid` as a reference to the element ? – adeneo Jul 01 '16 at 21:42
  • @adeneo Oh I was getting confused it is the global context, and I didn't know a element with a Id was added to the window object under the same id name. Can you point me to any documentation that says that a element with a Id is added to the window object? – ksrb Jul 01 '16 at 21:46
  • http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – adeneo Jul 01 '16 at 21:48
  • @adeneo Thanks, here's a additional relevant post http://www.2ality.com/2012/08/ids-are-global.html. – ksrb Jul 01 '16 at 21:48

1 Answers1

1

This was a case of confusing myself, and thinking that a handler bound in a HTML attribute somehow had a different execution context.

The handler still executes in the global scope/window object. Therefore as expected the event object in the function refers to the window.event object and the someid object refers to window.someid.

<input type='text' id='someid' 
 onclick="
   clickHandler(this,
                event,  //window.event
                someid)" //window.someid'/>

The automatic creation of window object for elements with unique ids is something I was not aware of which was pointed out in the question's comments see:

Do DOM tree elements with ids become global variables?

Community
  • 1
  • 1
ksrb
  • 1,797
  • 12
  • 22