Using an Object Id with JavaScript

Using an Object Id with JavaScript

By Shawn Olson

Posted on 08.25.04

For a web designer, one of the most powerful features of JavaScript is its ability to manipulate the visual qualities of objects on a web page in real time. With JavaScript you can tell a browser to display content in red one minute and then green the next.

The problem with a page that has many objects that you want to control with similar functions is keeping track of which element you need to refer to. If a page has a dozen photos, and you want to work with each individually, how do you keep track of them?

The solution is the ID attribute of an HTML element. Any element inside the body of an HTML document may have a unique ID which you place in its opening tag. For example, the two images below have the following HTML:

<img src="http://www.shawnolson.net/smo/media/smotograph.gif" id="exampleA" alt="Example A"/>

<img src="http://www.shawnolson.net/smo/media/cglogo.png" id="exampleB" alt="Example B"/>

Example AExample B
Example AExample B

WidthHeight


Notice the id="exampleA" and id="exampleB". We can use those ids when calling functions to make sure that the effect of a function is applied to the desired element only. So say we write a function to change the sizes of those image called changeImgSize(objectId,newWidth,newHeight). We could now control the new size of the image by referencing its ID and passing a new size in the function. To change exampleA to 50 x 100 we would use the following line:

changeImgSize(‘exampleA’,50,100)

The way that changeImgSize() references the specific object is by a built-in method of the document object in JavaScript called getElementById(). To affect any specifically labeled object in your web page, simply refer to it with “document.getElementById("myObject")” (replacing “myObject” with the desired object).

changeImgSize() is available at http://www.shawnolson.net/scripts/public_smo_scripts.js. Please include credit when using this script and read this site's Terms & Conditions before using.
Copyright © 2004-2008 by Shawn Olson.
Shawn Olson Creative Arts
sitemap RGB Color Columbus Photography Free Word Search Maker monty hall game Hangman John Dewey