Saturday, May 15, 2010

HTML5 Event Handlers

In the HTML 5 Spec there are phrases like:
If the script is from an external file, fire a simple event named load at the script element.
The question is, how do you catch this event? It turns out, I was worried about nothing but along the way I learned a lot of neat stuff.

Lets say you have:
<script onload="myfunction()">
Can myfunction be inside the file that is loaded? Turns out it can. I did not see where that was spelled out in the spec but it seems to work. But wait. Where is the event? I mean, how do I get the event passed to my function?

Turns out that you can do:
<script onload="'myfunction(event)'">
and the event is passed to you. But why "event" ? Where is that defined? Turns out, it is very nicely defined. In Section 7.1.6.1, the environment is very precisely defined using terms from the new EMCAScript 5 doc. It is also educational to write a simple html file and use firebug. Here is m file:

<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<script type="text/javascript">
function myfunc(event) {
alert('hi');
}
</script>
<title>Temp</title>
</head>
<body>
<form>
<input type='text' onmouseover='myfunc(event);'/>
</form>
</body>
</html>
  1. Load the file into Firefox (I called it "temp.html") and open
    Firebug. You might want to hit reload after you open the firebug
    window so that firebug sees the page load.

  2. Now pick the Script tab in Firebug.

  3. Mouse over the input element and an alert will pop up.

  4. Acknowledge the alert.

  5. Now in the subtab in Firebug, there is probably something that
    says "temp.html". Pull that down and it will show a second source
    called temp.html/event: function onmouseover(event) ...

  6. When you pick that you see:

    function onmouseover(event) {
    myfunc(event);
    }

  7. Now set a break point on line 2 and mouse over the input field
    again to trigger the event.

  8. While you are stopped in the break point inside the mouse over
    event handler, look at the Watch area on the right. Notice
    that this is set to the input tag. And also notice the
    scopeChain has
    1. event

    2. the input tag

    3. the form element

    4. the Document

    5. the Window (the global space)

    This is spelled out in section 7.1.6.1.


Note that since the form element is part of the environment, the elements of the form element are readily available. But remember that this is the context before myfunc is called. If you single step to inside myfunc and then review the scopeChain, you will see that only the Window is available. That is because Javascript uses static scoping.

No comments:

Post a Comment