Friday, February 25, 2011

How Not to do onclick

Check out the following code, which is live in this page.

<!DOCTYPE html>
<html>
<body>
<input type="button" value="0" id="a" onclick="increase()"/>
<input type="button" value="10" id="b"/> <script> function increase(){ this.value = Number(this.value) + 1; } document.getElementById('b').onclick = increase; </script> </body> </html>

In my chrome and firefox, clicking on the first button does nothing, while clicking on the second one increases the number by 1. If we open up firebug and print out the onclick properties for the two elements, we can see why the first one does not work.

> document.getElementById('a').onclick
function onclick(event) {
  increase()
}

> document.getElementById('b').onclick
function increase(){
 this.value = Number(this.value) + 1;
}

The first one has a function called onclick wrapped around the call to increase. So, in the first case, increase gets called as a global function which means that this will be bound to the global object. In the second case increase is called as a method of the input element.

Why this distinction? I don't know. What do you need to know? 1) Use the second form for this homework and 2) always use a good javascript library for setting up and handling events; like jQuery, which you will start using next week.

2 comments:

  1. This is a little late but here's a good related resource that I've found: Unobtrusive Javascript

    http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

    ReplyDelete