Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does browser handle inline javascript events?

I need to pass event object and event origin object to handling function. I believe I understand how external JavaScript works:

<input id="input2"/>
<script>
function getKey2(e) { alert(this.id+e.keyCode); }
document.getElementById("input2").onkeypress = getKey2;
</script>

The onkeypress method is defined on input2 DOM, so this points to it and event object is passed as the first argument to the function, but I am confused with inline JavaScript:

<input id="input1" onkeypress="getKey1(this,event)"/>
<script>
function getKey1(obj,e) {
    alert(obj.id+e.keyCode);
}
</script>

The first argument, this, should be Window object, but when it is copied to obj on the event, it is event origin object, the input1 from DOM. The second argument, event, should be global event object, but when called, event object is passed to the function. Apparently, my deduction is wrong - how does the call work?

Long story short: why the object values in the following chars are not the same?

              | name   object value
----------------------------------
in onkeypress | this   Window
in getKey1    | obj    DOM input1


              | name   object value
----------------------------------
in onkeypress | event  global event
in getKey1    | e      keypress event

fiddle here

like image 741
Jan Turoň Avatar asked Sep 13 '25 19:09

Jan Turoň


2 Answers

The W3C DOM specification states two bindings for inline events:

  1. this is bound to the element upon which the inline event was defined;
  2. A local variable with the name event is introduced. (IE doesn't do this but the same syntax works for inline event because event will be treated as window.event in IE.)

In HTML5 the information is buried under 6.1.6.1 Event handlers. The two parts are spread out:

When an event handler content attribute is set [that is, when an inline event is set] .. Let body [of the synthesized function declaration] be the event handler content attribute's new value .. Let the function have a single argument called event. [Note that onerror is a special.]

.. Let Scope [or this] be the result of NewObjectEnvironment(the element's object, Scope). [This is chained with other environment contexts such as the Form (if it exists) and the Global Context.]

like image 68
user2246674 Avatar answered Sep 15 '25 09:09

user2246674


no, this will be the dom object on which the event was triggered, in this case the <input> were the onkeyup attribute was set and where the browser will find a handler.

We are going to play a little more with those events: http://jsfiddle.net/nFfEp/

For better understanding about the event triggering and handling this is a very useful document: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow

like image 42
Edorka Avatar answered Sep 15 '25 09:09

Edorka