Web Designing for Beginners - DHTML - A Product by Fastforward - Jasubhai Digital Media

Overview

Dynamic HTML is the term used to mean several ways to enhance static web pages. Dynamic HTML effects using a combination of HTML, Cascading Style Sheets, and JavaScript.

Note: This tutorial covers HTML Version 4.0, the latest version as of date. Some additional features that are widely and consistently implemented in browsers are also covered.
Topics
DHTML - An Introduction
DHTML and JavaScripts
Dynamic Positioning
Properties of Style
JavaScript
Dynamic Styles
Inline Styles
Changing the Rules
Events

Click FORWARD to continue

Scope

  • Positioning; precisely placing blocks of content on the page and, if desired, moving these blocks around.
  • Style modifications; on-the-fly altering the aesthetics of content on the page.
  • Event handling; how to relate user events to changes in positioning or other style modifications.


DHTML- An Introduction

Click FORWARD to continue
1 of 9

Dynamic HTML - An Introduction

  • Many web pages today are dynamic and interactive applications rather than static pages.
  • Dynamic HTML is the term used to mean several ways to enhance static web pages.
  • DHTML allows elements on a page to change at any time.
  • Traditionally this was done at the server end and then the changed data was sent to the browsers. This was time consuming and restricting the dynamism of the page.
  • DHTML is defined by a construct called the Document Object Model (or "DOM"). This model describes each page element and which of its characteristics may be modified, and how so. As you can imagine, Netscape and Microsoft do not share a common DOM.
  • DHTML standardization rest strongly on the success of a standardized DOM.
  • Dynamic HTML effects using a combination of HTML, Cascading Style Sheets, and JavaScript. The Document Object Model, described earlier, provides a programming interface between HTML/CSS and JavaScript.
  • DHTML is still evolving and becoming more and more powerful.


DHTML- DHTML and Javascript

2 of 9

DHTML and JavaScript

Once you understand the basic concepts of dynamic positioning using JavaScript in the coming pages, the possibilities of making a web page dynamic is endless. With imagination, practice and proficiency in JavaScript, you can create highly interactive web pages. Some of the possibilities are:
  • Animation: images contained in a positioned block can be moved around the page following a certain path.
  • Drop-down menus: modifying clipping regions allows you to show or hide portions of a content block. To create a drop down menu, you would initially show only the top strip of the block containing the menu choices. When the user triggers the menu to drop, you change the clipping region to display the vertical length of the menu chosen. We'll look at triggers from user events later in this article.
  • Content-swapping: by positioning multiple blocks of content at the same spot on the page, yet keeping all but one block invisible, you can quickly swap a new block of content into place by changing their visibility properties. Alternatively, by keeping two overlapped blocks visible, you can modify their clipping regions in such a pattern as to produce a "transition" effect.


DHTML - Dynamic Positioning

3 of 9

Dynamic Positioning

Using DHTML, you can define a block of HTML content and precisely position it on the page.

There are two ways to position a block of content: Netscape's <LAYER> tag or Cascading Style Sheet Positioning (CSSP). Although Netscape's proprietary tag is simple to use, it is only supported within Netscape. Alternatively, CSSP is supported by both Netscape and Microsoft, so we will look at positioning using the style sheet syntax. There is no real loss of functionality, as layers and CSSP blocks behave nearly identically.

Hitting the Spot

Typically, a block of content is contained within <DIV> tags. Imagine, then, that you would like to create a small block of content -- an image plus a mail to hyperlink:

    <DIV>
    <A HREF="mailto:me@yahoo.com.com">Mailme!</A><BR>
    <IMG 	SRC	= "mail.gif"
        width	= 30
        height	= 15
        alt	= 'Mailbox'
        >
    </DIV>

To position this block, however, you must tell the <DIV> block to use a style sheet. A style sheet, as you may know, defines display characteristics. Style sheets can either be pre-defined, and applied to tags as style sheet classes, or defined on-the-fly. Typically, when using CSS Positioning, you define the block's style on-the-fly. We do this by using the STYLE attribute for the <DIV> tag. The STYLE attribute contains a string which lists each desired style property and its value. For example:

    <DIV ID="mailblock"
        STYLE="position:absolute;
        width:auto;
        height:auto;
        left:400px;
        top:50px;
        background-color:white;">

    <A HREF="mailto:me@yahoo.com">Mail me!</A><BR>

    <IMG 	SRC	= "mai.gif"
        width	= 30
        height	= 15
        alt	= "Mailbox"
        >

    </DIV>

In the above example, we've first added the ID attribute to assign an identifier to this content block. This may become useful later when manipulating this block using JavaScript. Next, the STYLE attribute contains a list of property parameters and values. Notice that a colon separates the parameter (left) from the value (right) and a semicolon separates each parameter/value pair from the next. In this case, we've specified that mailblock should be absolutely positioned on the page (meaning that it is not fixed relative to the position of any other page elements), with automatic width and height, 400 pixels right from the left edge of the browser's content window and 50 pixels down from the top edge of the browser's content window.

Simple enough except for one bit of trouble i.e. we don't know the size of the user's screen or browser window! Thus, we don't really know where 400 pixels to the right will land this block relative to the rest of the page. This could result in an ugly layout. The solution to precise, but adaptable, layouts is to use relative positioning. Imagine, for example, that we want mailblock to appear slightly indented leftwards from the upper-right corner of the page. To achieve this position, we will create a two-level <DIV> block -- a parent and a child:

    <DIV ID="mailblock_parent"
        ALIGN="right">
    <DIV ID="mailblock_child"
        STYLE="position:relative;
        width:auto;
        height:auto;
        left:-10px; top:0px;
        background-color:white;">
    <A HREF="mailto:me@yahoo.com">Mail me!</A><BR>
    <IMG 	SRC	= "mail.gif"
        width	= 30
        height	= 15
        alt	= "Mailbox"
        >
    </DIV>
    </DIV>

In this example, the parent <DIV> block contains, as a child <DIV> block, the content for the mailto link and image. The parent block is aligned to the right edge of the page. The child block, which contains the actual content, is dynamically positioned relative to the parent, 10 pixels to the left of the parent's left edge.


DHTML - Properties of Style

4 of 9

Properties of STYLE

Clearly, positioning your block of content depends upon the specified STYLE properties. Several documents on Web contain references to the positioning properties available for style sheets -- two worth reviewing are Microsoft's CSS Attributes Reference (under "Positioning Properties") and Netscape's Defining Positioned Blocks of HTML Content.

Employing the various STYLE properties gives you powerful control over the position and look of the blocks of content on your page. Conceptually, then, when we think in DHTML we think of a page as made up of one or more blocks.

Once the blocks have been put into place, you can -- at any time -- change their properties. Position, background, clipping region, z-index -- with the help of JavaScript.


DHTML - Using javascripts to make your page dynamic

5 of 9

Using JavaScripts to Make Your Page Dynamic

Once you've positioned a content block on the page using <DIV> tags in your HTML, you can use JavaScript to modify its properties. This has many possible consequences: you can move the entire block up, down, left or right. You can change its background color, or change the clipping region, causing more or less of the block to be visible. Speaking of visibility, you can even hide or show the entire block in an instant via the visibility property.

How, then, does JavaScript access the style properties of the content block? The answer is twofold:

1. Assuming that you are not familiar with JavaScript, you may start knowing it this way that data structures in javascripts are represented as objects, and each object has a set of properties. JavaScript statements can read or write to the properties of an object.

2. Content blocks contained in <DIV> tags are exposed as objects to JavaScript by the Document Object Model. This means that, following the object and property specifications defined by the DOM, JavaScript can access the style sheet properties of the content block.

Let's recall our example content block, mailblock. In its simple form:

    <DIV ID="mailblock"
        STYLE="position:absolute;
        width:auto;
        height:auto;
        left:400px; top:50px;
        background-color:white">
    <A HREF="mailto:me@yahoo.com">Mail me!</A><BR>
    <IMG 	SRC	= "mail.gif"
        width	= 30
        height	= 15
        alt	= "Mailbox"
        >
    </DIV>

Because Netscape and Microsoft do not currently share compatible DOMs, the above block is exposed to different objects in each browser. For now, we'll consider each case separately.

In Netscape's DOM, each <DIV> block takes the form of a Layer Object. In Microsoft, each block is exposed as a DIV object, which in turn possesses a STYLE object, whose properties reflect the familiar style attribute properties.This might sound confusing, but it's all a matter of syntax. Let's first consider how you would construct a JavaScript reference to mailblock. You use the identifier specified in the ID attribute.

Microsoft:

document.all.mailblock

Netscape:

document.layers["mailblock"]

Now, let's consider the background color property for mailblock. The CSS property for the background color was "background-color" as specified in our <DIV> tag. When reflected via the DOM, however, this property takes on a different name between browsers.

Microsoft:

document.all.mailblock.style.backgroundColor

Netscape:

document.layers["mailblock"].bgColor

Knowing that, we can easily create a JavaScript statement which would change the background color of mailblock to green.

Microsoft:

document.all.mailblock.style.backgroundColor="green";

Netscape:

document.layers["mailblock"].bgColor="green";

Similarly, we can modify the top and left style properties which will move the block on-screen. Thus, once we know the correct DOM property for the style sheet left property, we can move mailblock directly to the left edge of the page:

Microsoft:

document.all.mailblock.style.left="0px";
OR
document.all.mailblock.style.pixelLeft=0;

Netscape:

document.layers["mailblock"].left=0;


DHTML - Dynamic Styles

6 of 9

Dynamic Styles

Like JavaScript, Cascading Style Sheets are their own in-depth web authoring topic. Because our focus is on DHTML, we shall concentrate on the web authoring technologies.

The style sheet determines how, aesthetically, the document is rendered on the screen. There are several ways to apply styles using style sheets. You can define styles which apply globally to all HTML elements of a certain type.
For example, you might create a style sheet which specifies that all <H3> elements be bold (font-weight) and red (color).

You may also define style "classes," which are predefined styles applied to an element on-demand.
For example, you might specify that the style class "redbold" contains the styles bold (font-weight) and red (color). This redbold class would only apply to elements in which you demand it; e.g. <BLOCKQUOTE CLASS="redbold">.

Lastly, as you've already seen, you can define and apply styles on-the-fly, using the STYLE attribute for an element tag;
e.g. <H4 STYLE="color:red; font-weight:bold;">. These on-the-fly styles apply only to the tag in which they are specified.

Both Microsoft and Netscape support CSS, although Microsoft supports additional style properties which do not exist under Netscape. The critical difference between the browsers, however, is the degree to which their CSS support is dynamic.

Within Microsoft's Internet Explorer, you can, via JavaScript, modify many of the properties of a style sheet or an element's individual style. These changes will be immediately reflected on-screen -- so, if you changed the redbold class's color property to blue, any on-screen text using the redbold class will suddenly change to blue. Similarly, you can change any style property for those elements which possess inline ("on-the-fly") styles.

Netscape, on the other hand, is not so accommodating. While there is an interface to style sheets via JavaScript , you can only use JavaScript to define styles before they are rendered. By and large, this would be used as a slightly more flexible replacement for defining your styles rather than using standard CSS syntax. On the other hand, using standard CSS syntax would maintain compatibility between browsers. Netscape's support for CSS via JavaScript is not useful nor dynamic, since changes applied to styles once the page has been rendered do not appear on-screen.


DHTML - Inline Styles

7 of 9

Inline Styles

Inline style is a style which applies only to an individual element rather than all elements of a certain type or class. Typically, an inline style is defined using the STYLE attribute for the element's tag; e.g. <H2 STYLE="color:blue;">.

Within MSIE, you can use JavaScript to modify an inline style at any time. The modification will take effect on-screen immediately. You do this using the Style Object, which we looked at earlier with Dynamic Positioning. The Style Object in MSIE's DOM supports every property which CSS supports for styles. However, the property names differ slightly between CSS syntax and DOM syntax. Fortunately, the naming differences follow a rule. Consider the CSS property font-weight. The corresponding Style Object property is named fontWeight. Similarly, the CSS property text-align maps to the Style Object property textAlign. Of course, color retains the same name in both syntax's. As you can see, then, CSS property names simply lose their hyphen and capitalize the first letter following the hyphen when used in JavaScript syntax.

It is not so confusing though that might sound, let's look at an example which illustrates just how easy changing styles can be. Imagine that you have the following HTML element:

<P ID="selectrule" ALIGN="left" STYLE="color:blue; font-weight:normal;">
    Please select one item below.
</P>

Now, some series of events occur and the user fails to follow instructions. So, you'd like to emphasize the exhortation:

    document.all.selectrule.style.color="red";
    document.all.selectrule.style.fontWeight="bold";

When the above statements are executed, the text associated with the element named selectrule will become red and bold. Of course, you can set the element back to its original state by setting color back to "blue" and fontWeight back to "normal".

Notice that JavaScript statements are modify the styles directly associated with a particular element. You can always do this, even if the element's style wasn't defined inline, but was inherited from a class or global style sheet. No matter how the element gained its original style, whether inline or by style sheet, directly modifying the style in the above manner only applies to the individual element. For this reason, this form of JavaScript dynamic styles is always an inline style.


DHTML-Changing the Rules

8 of 9

Changing the Rules

Modifying the style of an individual element is very precise, but sometimes you may want to have a more global effect: perhaps you'd like to modify a style defined by a style sheet as a class or global style. Such a modification would have a ripple-effect, immediately re-rendering all elements on the page which are subject to that style sheet.

Below is a style sheet definition which specifies two styles: a global style which applies to all <H3> element (blue, arial font family, large size), and a generic style class named warning (red, bold, italic)which will apply to any element which uses that class.

<STYLE ID="sheet1">
    H3 { color:blue; font-family:"Arial"; font-size:large; }
    .warning { color:red; font-weight:bold; font-style:italic; }
</STYLE>

Your goal, once the document has been rendered according to the above style sheet, is to modify this style sheet via JavaScript such that any changes are dynamically reflected on-screen. To do this, you'll need to learn some new terminology. Each "style definition" in the style sheet is known as a "rule". Thus, the line defining the style for H3 is one rule, while the line which defines the warning class is a second rule.

In Microsoft's Document Object Model, you access a style sheet through the styleSheets[] array (aka "collection"). A single style sheet is defined as everything between a set of <STYLE>...</STYLE> tags. The above example, then, is one style sheet. If it were the first instance of such tags in your source code then it would be the first style sheet, as well. You access the first style sheet via JavaScript using the reference:

    document.styleSheets[0]

That said, within each styleSheet object is a rules collection. This array contains an entry for each rule within the style sheet. Therefore, you would access the first rule -- the H3 rule -- of this style sheet as:

    document.styleSheets[0].rules[0]

And the second rule -- the warning class -- as:

    document.styleSheets[0].rules[1]

Each rule object possesses a style object. And it is through that style object which you can modify the rule. What?? Example: You want to change the H3 rule in this example so that its color becomes yellow:

    document.styleSheets[0].rules[0].style.color="yellow";

Now you want to change this rule's font family to courier:

    document.styleSheets[0].rules[0].style.fontFamily="courier";

You can modify any style property for the rule, even one which wasn't specified in the original style sheet. Thus, if you would suddenly like to make all H3 text on the page italic:

    document.styleSheets[0].rules[0].style.fontStyle="italic";

Any of the above JavaScript statements will apply the changes to all <H3> elements on the page. Similarly, making any changes to the style object for the warning class rule (document.styleSheets[0].rules[1].style.property) will apply all changes to any tags which specify the attribute CLASS="warning"; e.g. <P CLASS="warning">.


DHTML - Events

9 of 9

Events

Many different types of event can occur on a Web page, most of them caused by the user. He or she might click on a button (click event), might move the mouse over an element (mouseover event), or move the mouse off an element (mouseout event). The user may submit a form (submit event) or resize the browser window (resize event). Additionally, some events occur without direct user intervention the page may finish loading (load event), for example.

The Document Object Model also defines types of events and their characteristics, such as to which elements they apply. More exactly, though, you manipulate and control events using JavaScript syntax. Once again, then, the handling of events is not exactly the same between Microsoft and Netscape browsers, at least until a standardized DOM comes along.

Managing events can be relatively simple or quite complex, depending on the ambitions of your project. Since this is an introduction, we'll focus mainly on event basics. Fortunately, basic events are handled most similarly between browsers.

Event Handlers

Events occur on a Web page whether you choose to act on them or not. When the user moves the mouse over an element, a mouseover event occurs. If you would like to leverage this event as a trigger for some dynamic action, you must construct an event handler.

An event handler is created as an attribute for the tag which defines the element at which you wish to catch the event. Event handler attribute named follow the syntax onEventname, and they accept JavaScript statements as their action. For example, the following tag creates a hyperlink with a mouseover event handler specified.

<A HREF="page.html"
   onMouseOver="changeStatus('Read this page');
   return true">
Click here
</A>

The onMouseOver event handler catches a mouseover event. When this event occurs at this element, a JavaScript function is called named changeStatus(). This is a fictional function, you can imagine that it might exist to change the message on the browser's status bar. Any JavaScript statement is allowed in an event handler, so we could also execute direct statement rather than call a function. For example, suppose that a mouseover for this element in Internet Explorer should modify a style sheet's color property:

<A	HREF="page.html"
    onMouseOver="document.styleSheets[0].rules[0].style.color='blue'"
    >
    Click here</A>

The above example assumes Internet Explorer, since style sheet modifications aren't supported in Netscape. We also assume that a style sheet exists in this document.

There are some important caveats to keep in mind.

Both browsers support additional events for detecting keypresses and other mouse actions, while Internet Explorer supports additional events above and beyond Netscape's. Secondly, you must keep in mind that not every event is applicable to every element. This also varies between browsers.
For example, within Netscape a mouseover event only applies to a hyperlink <A>, area <AREA> or layer <LAYER>. Yet, within Internet Explorer, you can apply a mouseover event to almost any element, including images <IMG>, and paragraphs <P>.

In general, the above rule holds between browsers: Netscape restricts each event to certain limited elements, while Internet Explorer allows most events to be handled at most elements.