Using an Object Id with JavaScript

Using an Object Id with JavaScript

By Shawn Olson

Posted on August 25th, 2004

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 (click here for a robust video tutorial and reference files on manipulating styles with JavaScript.). 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 A Example B
Example A Example B
Width Height

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-2009 by Shawn Olson.

Subscribe to this guestbookComments on Using an Object Id with JavaScript

William Moraes said:

hey man, fix up your button!
on the button event you should put this:

changeImgSize(document.exampleForm.Example.value,document.exampleForm.width.value,document.exampleForm.height.value); return false

you forgot the "return false". without this the page will send all data from the form to the action, and reload the page as well.

:) (sorry for my bad english)

sitemap RGB Color Columbus Photography Free Word Search Maker monty hall game Hangman John Dewey