Using an Object Id with JavaScript
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 |
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.
- Related Topics
William Moraes
Dec 21, 2008
Reply
Shawn Olson
Dec 23, 2008
Reply