Uncle Jim's Web Designs and Tutorials

This is part nine of a series on Dynamic HTML


ID, CLASS and STYLE

The binding between <DIV> tags and javascript is through CSS (Cascading Style Sheets) syntax. Knowing when to use ID, CLASS and STYLE is very important in obtaining the desired results.

ID attribute:

The ID attribute is used to associate a name with a DHTML object. The associated name is what is required to access the object from javascript by other than it's numeric position in an array, as in the following example code:

<DIV id="Dbutton1">    </DIV<
<DIV id="Dbutton2">    </DIV<
<DIV id="Dbutton3">    </DIV<

Then, you simply specify the style inside the style sheet or in the page itself that will only apply to that particular DIV, as in the below example:
#Dbutton1 {
	background-color:blue;
	color:white;
	}

#Dbutton1 {
	background-color:red;
	color:blue;
	}

#Dbutton1 {
	background-color:white;
	color:red;
	}

This will give you the following results:
This is white text on a blue background.
This is blue text on a red background.
This is red text on a white background.


CLASS

The CLASS attribute is used to define CSS attributes to be shared by a group of objects. In the case of the Buttons above , the CLASS might declare them all to be grey with a thin border. Although it would be nice to be able to modify the values in a class of objects , we are not yet able to accomplish this. For now, DHTML is limited to addressing individual objects when modifications of the values is desired, like the below example code:

.Button1
	{
	background-color:gray;
	border: thin solid black;
	}

STYLE

The STYLE attribute is used to define CSS attributes associated with a particular object. Though somewhat similar to the ID attribute, those attributes you intend to modify using javascript and DHTML should be individually defined in the STYLE attribute of the HTML element involved.

Declaring a DIV to be suitable for DHTML usually involve the incorporation of all three attributes, as in the below code example:


#AnID		{

		}
.Aclass		{
		background-color:#FFFFCC;
		color:blue;
		}

Then, you would code the following:
<DIV id="AnID" class="Aclass" style="left:10;top:10;width:100;height:100;position:absolute;">Hello world</DIV>

This would result in the display of a 100x100 box with a pink background and blue text at the top, left of your page.

Further examination shows that top and left indicate the location at which the object will appear in the browser window. However, using top and left does not absolutely mean you will get the desired effect. This usually depends on the value assigned to the position attribute. But for DHTML, position:absolute is most common usage and causes the <DIV> to be positioned without consideration of where other objects were located.

Next, we get into Binding Javascript to DIV elements.