spacer
Yehuda Shiran August 3, 2000
Using "this" in Event Handling
Tips: August 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

When you call a function via an event handler, you may refer to the form element which triggered the event handler, such as a text field or a button. Every form element is an object. You can use the keyword this to refer to the "current" object. The following entry field initially displays the string "email..." but changes to "thank you" once you modify it (click outside the field to signal the change's end):

There are two ways to implement this effect, with and without this. The following script refers to a form element without using the this keyword (this script was used for the field above):

<SCRIPT LANGUAGE="JavaScript">
<!--

function process1() {
  document.forms[0].elements[0].value = "thank you";
}

// -->
</SCRIPT>
<FORM>
<INPUT TYPE="text" NAME="myField" VALUE="email..." onChange="process1()">
</FORM>

We can implement the same effect with the this keyword. Convince yourself that the effect is the same:

Here is the script:

<SCRIPT LANGUAGE="JavaScript">
<!--

function process2(callingElement) {
  callingElement.value = "thank you";
}

// -->
</SCRIPT>
<FORM>
<INPUT TYPE="text" NAME="myField" VALUE="email..." onChange="process2(this)">
</FORM>

This form is preferred because you can change the element's position, name, or any other optional attribute (other than the event handler) and the script will still work without modifications. The keyword this refers to the element providing the event handler. In this case, the value of this is equal to document.forms[0].elements[0]. When the function process() is called, the value assigned to the callingElement parameter is this, so callingParameter.value is equivalent to document.forms[0].elements[0].value.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business