Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

JavaScript - A Simple Example of "This"

Last Update: 5.3.2008

Introduction

this is a JavaScript keyword that can be used to reference "self" or "me", instead of using a more complicated getElementById() method. It's handy for adding simple actions to elements using an inline action. In this example, putting a mouse cursor over each image below will enlarge it.


Demonstration

Mouseover each of the images below, and watch it expand and contract. When one of the images is rolled-over, it's width is set to 64 pixels, double it's original size. When the mouse rolls off the image, the image's width is set back to the original size of 32 pixels.


Code

Here is the important part of the image tag:

<img src="..." onmouseover="this.width='64';" onmouseout="this.width='32'" />

Using the "this" keyword allows us to directly access the properties of the image, rather than having to specify an ID, and use getElementById.

For more information on "this", take a look at quirksmode's explanation of the 'this' JavaScript keyword.


Credits

Images used in this example are courtesy of the good folks at IconBuffet.com.


Looking for more?

Back to Pew Pew Laser Articles

Contact Me