BUY THIS BOOK

Safari Books Online

What is this?

Looking to Reprint this content?


Dynamic HTML: The Definitive Reference
Dynamic HTML: The Definitive Reference

By Danny Goodman

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: The State of the Art
It wasn't all that long ago that becoming a web page authoring wizard required little more than an understanding of a few dozen Hypertext Markup Language (HTML) tags, and perhaps modest experience with a scanner and a graphics program to generate a corporate logo image file. Armed with that knowledge, you could start an Internet design business or become the online content guru at a Fortune 500 company. Ah, those were the good old days...about two years ago.
The stakes are much higher now. The hobby phase is over. The Internet is big business. Competition for visitor "hits" is enormous, as it becomes more and more difficult to get your site noticed, much less bookmarked. Sensing that the authoring world wanted more out of HTML than a poor imitation of the printed page, the web browser makers and the Internet standards bodies have been expanding the capabilities of web pages at a feverish pace. These changes are allowing us to make our pages more dynamic—pages that can "think and do" on their own, without much help from the server once they have been loaded in the browser. But at the same time, what we authors have to do to make our new, fancy content play on all the browsers is constantly changing.
As a result, it is no longer possible to become a web content guru by studying the formal HTML recommendation published by the World Wide Web Consortium (W3C). Adding effective Dynamic HTML (DHTML) content to your pages requires an understanding of other technologies, specified by additional standards that exist outside the charter of the original HTML Working Group. In this chapter, we'll discuss the variety of standardization efforts that are currently underway. You should begin to appreciate both how far the browser makers have come and how far they have to go in providing us with compatible DHTML capabilities at a suitably high level.
There is no such thing as a single Dynamic HTML standard. DHTML is an amalgam of specifications that stem from multiple standards efforts and proprietary technologies that are built into the two most popular DHTML-capable browsers, Netscape Navigator and Internet Explorer, beginning with Version 4 of each browser.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The Standards Alphabet Soup
There is no such thing as a single Dynamic HTML standard. DHTML is an amalgam of specifications that stem from multiple standards efforts and proprietary technologies that are built into the two most popular DHTML-capable browsers, Netscape Navigator and Internet Explorer, beginning with Version 4 of each browser.
Efforts by various standards bodies and working groups within those bodies are as fluid and fast moving as any Internet-related technology. As a savvy web content author these days, you must know the acronyms of all relevant standards (HTML, CSS, CSS-P, DOM, and ECMA for starters). You also have to keep track of the current release of each standard, in addition to the release that is incorporated into each version of each browser that you are developing for. Unfortunately for the authoring community, it is not practical for the various standards bodies and the browser makers to operate in complete synchronicity with each other. Market pressures force browser makers to release new versions independent of the schedules of the standards bodies.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Version Headaches
As a further complication, there are the inevitable prerelease versions of browsers and standards.
Browser prereleases are sometimes called "preview editions" or "beta" versions. While not officially released, these versions give us a chance to see what new functionality will be available for content display in the next-generation browser. Authors who follow browser releases closely sometimes worry when certain aspects of their current pages fail to work properly in prerelease versions. The fear is that the new version of the browser is going to break a carefully crafted masterpiece that runs flawlessly in released versions of the browser.
Somewhere between the releases of Netscape Navigator 2 and 3, I learned not to fret over breakages that occur in prerelease browser versions. Of course, it is vital to report any problems to the browser maker. I refuse, however, to modify my HTML or scripting code to accommodate a temporary bug in a prerelease version of a browser, as it is being used by an extremely small percentage of the population. My feeling is that anyone who uses a prerelease browser does so at his or her own risk. If my pages are breaking on that browser, they're probably not the only ones on the Net that are breaking. A user of a prerelease browser must understand that using such a browser for mission-critical web work is as dangerous as entrusting your life's work to a beta version of a word processing program.
On the standards side, working groups usually publish prerelease versions of their standards. These documents are very important to the people who build browsers and authoring tools for us. The intent of publishing a working draft is not much different from making a prerelease browser version public. The goal is to get as many concerned netizens as possible looking over the material to find flaws or shortcomings before the standard is published.
And speaking of standards, it is important to recognize that the final releases of these documents from standards bodies are called not "standards" but "recommendations." No one is forcing browser makers to implement the recommendations. Fortunately, from a marketing angle, it plays well to the web audience that a company's browser adheres to the "standards." Eventually—after enough release cycles of both standards and browsers allow everyone to catch up with each other—our lives as content creators should become easier.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
HTML 4.0
The most recent release of recommendations for HTML is Version 4.0 (http://www.w3.org/MarkUp/). As you will see in more detail in Section 7.1, HTML 4.0 has a considerably larger vocabulary than the previous release that is in common use, Version 3.2. Surprisingly, this time around the standard is way ahead of the browser makers. Many of the new features of HTML 4.0 are designed for browsers that make the graphical user interface of a web page more accessible to users who cannot see a monitor or use a keyboard. The new tags and attributes readily acknowledge that a key component of the name World Wide Web is World. Users of all different written and spoken languages need equal access to the content of the Web. Thus, HTML 4.0 includes support for the alphabets of most languages and provides the ability to specify that a page be rendered from right to left, rather than left to right, to accommodate languages that are written that way.
Perhaps the most important long-term effect of HTML 4.0, however, is distancing the content of web pages from their formatting. Strictly speaking, the purpose of HTML is to provide structural meaning to the content of pages. That's what each tag does: this blurb of text is a paragraph, another segment is labeled internally as an acronym, and a block over there is reserved for data loaded in from an external multimedia file. HTML 4.0 is attempting to wean authors from the familiar tags that make text bold and red, for example. That kind of information is formatting information, and it belongs to a separate standardization effort related to content style.
In the HTML 4.0 world, a chunk of text in a paragraph is bold because it is tagged as being an element that requires emphasis. Whether it is bold or italic or green is not defined by the HTML vocabulary, per se. Instead, the HTML passes the formatting decision to a style definition. When the text is viewed in a browser on a video monitor, the color may be green and the style italic, but when the same page is viewed through a projection system, it may be a different shade of green, to compensate for the different ambient lighting conditions, and bold, so it is more readable at a distance. And when the content is being read aloud electronically for a blind user, the voice speaks the tagged words with more emphasis. The key point here is that the content—the words in this case—was written and tagged once. Style definitions, either in the same document or maintained in separate files that are linked into the document, can be modified and enhanced independently of the content.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Style Sheets
A style sheet is a definition of how content should be rendered on the page. The link between a style sheet and the content it influences is either the tag name of the HTML element that holds the content or an identifier associated with the element by way of an attribute (such as the ID or CLASS attribute). When a style sheet defines a border, the style definition doesn't know (or care) whether the border will be wrapped around a paragraph of text, an image, or an arbitrary group of elements. All the style knows is that it specifies a border of a particular thickness, color, and type for whatever element or identifier is associated with the style. That's how the separation of style from content works: the content is ignorant of the style and the style is ignorant of the content.
The standardization efforts for style sheets are still trying to establish themselves, despite the fact that some versions have already been published. At the time the Version 4 implementations of Navigator and Internet Explorer were under construction, there were two separate, but related, style sheet efforts underway: Cascading Style Sheets Level 1 (CSS1) and Cascading Style Sheets-Positioning (CSS-P). The CSS-P functionality is being blended into the primary specification for the next version of CSS, Cascading Style Sheets Level 2 (CSS2). All CSS standards activity is under the auspices of the W3C (http://www.w3c.org/Style/). Chapter 10, provides a complete reference for all the style attributes available in CSS1 and CSS2.
The Cascading Style Sheets Level 1 recommendation lets authors define style rules that are applied to HTML elements. A rule may apply to a single element, a related group of elements, or all elements of a particular type (such as all P elements). Style rules influence the rendering of elements, including their color, alignment, border, margins, and padding between borders and the content. Style rules can also control specialty items, such as whether an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Document Object Model
When an HTML page loads into a scriptable browser, the browser creates a hidden, internal roadmap of all the elements it recognizes as scriptable objects. This roadmap is hierarchical in nature, with the most "global" object—the browser window or frame—containing a document, which, in turn, contains a form, which, in turn, contains form elements. For a script to communicate with one of these objects, it must know the path through the hierarchy to reach the object, so it can call one of its methods or set one of its property values. Document objects are the "things" that scripts work with.
Without question, the most hotly contested competition between Navigator and Internet Explorer has been how each browser builds its internal roadmap of objects. This roadmap is called a document object model (DOM). When one browser implements an object as scriptable but the other doesn't, it drives scripters and page authors to distraction. A lot of authors felt the sting of this problem when they implemented image-swapping mouse rollovers in Navigator 3. They soon discovered that images were not scriptable objects in Internet Explorer 3, so their IE 3 users were getting script errors when visiting the sites and moving their mice across the hot images.
In an effort to standardize this area, a separate working group of the W3C is charged with setting recommendations for an HTML Document Object Model (www.w3c.org/DOM/) that would become the common denominator among browsers (the HTML subgroup is only one branch of a larger DOM effort). This is an incredibly difficult task for a number of reasons: Netscape and Microsoft are often at loggerheads on DOM philosophy; technically the browsers aren't built the same way inside, making common implementation of some ideas difficult; and historically authors are familiar with their favorite browser's way of handling objects and don't want to learn an entirely new method.
Of all the standards discussed in this chapter, DOM is the least solid. From indications in the working drafts, even the first release won't cover some important categories, such as event handling. The issues around incompatible DOMs involve a long, uphill struggle that DHTML authors will face for a while. We will be tantalized by features of one browser, only to have our hopes dashed when we learn that those features aren't available in the other browser.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
ECMAScript
When Navigator 2 made its debut, it provided built-in client-side scripting with JavaScript. Despite what its name might imply, the language was developed at Netscape, originally under the name LiveScript. It was a marketing alliance between Netscape and Sun Microsystems that put the "Java" into the JavaScript name. Yes, there are some striking similarities between the syntax of JavaScript and Java, but those existed even before the name was changed.
Internet Explorer 3 introduced client-side scripting for that browser. Microsoft provided language interpreters for two languages: VBScript, with its syntax based on Microsoft's Visual Basic language, and JScript, which, from a compatibility point of view, was virtually 100% compatible with JavaScript in Navigator 2.
It is important to distinguish a programming language, such as JavaScript, from the document object model that it scripts. It is too easy to forget that document objects are not part of the JavaScript language, but are rather the "things" that programmers script with JavaScript (or VBScript). The JavaScript language is actually more mundane in its scope. It provides the nuts and bolts that are needed for any programming language: data types, variables, control structures, and so on. This is the core JavaScript language.
From the beginning, JavaScript was designed as a kind of core language that could be applied to any object model, and this has proven useful. Adobe Systems, for example, uses JavaScript as the core scripting language for Acrobat Forms scripting. The same core language you use in HTML documents is applied to a completely different object model in Acrobat Forms.
To head off potentially disastrous incompatibilities between the implementations of core JavaScript in different browsers, several concerned parties (including Netscape and Microsoft) worked with a European computer standards group now known only by its acronym: ECMA. The first published standard, ECMA-262 (www.ecma.ch/stand/ecma-262.htm
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
A Fragmenting World
As you will see throughout this book, implementing Dynamic HTML applications that work equally well in both Navigator 4 and Internet Explorer 4 can be a challenge unto itself. Understanding and using the common-denominator functionality among the various pieces of DHTML will lead you to greater success than plowing ahead with a design for one browser and crossing your fingers about how things will work in the other browser.
One more potential gotcha is that the same browser brand and version may not behave identically across different operating systems. Navigator 4 is pretty good about maintaining compatibility when you open a document in operating systems as diverse as Solaris and Windows 3.1. The same can't be said for Internet Explorer 4, however. Microsoft readily admits that some features (detailed in later chapters) are guaranteed to work only on Win32 operating systems (Windows 95, Windows 98, and Windows NT 4). Even features that should work on non-Win32 systems, such as style sheets, don't always translate well to, say, the Macintosh version of IE 4.
If the inexorable flow of new browser versions, standards, and authoring features teaches us anything, it is that each new generation only serves to fragment further the installed base of browsers in use throughout the world. While I'm sure that every reader of this book has the latest sub-version of at least one browser installed (and probably a prerelease edition of a new version), the imperative to upgrade rarely trickles down to all the users of yesterday's browsers. If you are designing web applications for public consumption, coming up with a strategy for handling the ever-growing variety of browser versions should be a top priority. It's one thing to build a DHTML-based, context-sensitive pop-up menu system into your pages for IE 4 users. But what happens to users who visit with Navigator 4, or IE 3, or a pocket computer mini-browser, or Lynx?
There is no quick and easy answer to this question. So much depends on your content, the image you want to project via your application, and your intended audience. If you set your sights too high, you may leave many visitors behind; if you set them too low, your competition may win over visitors with engaging content and interactivity.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Cross-Platform Compromises
Declaring support for industry standards is a noble act. But when each web browser maker is also out to put its stamp on the details of still-evolving standards, it's easy to see how a new browser release can embody ideas and extensions to standards that are not available in other browsers. With so many standards efforts related to Dynamic HTML in play at the release of both Netscape Navigator 4 and Microsoft Internet Explorer 4, implementation differences were bound to occur. This chapter provides an overview of each browser's approach to DHTML. It also explores some strategies that you might use for DHTML applications that must run identically on Navigator and Internet Explorer.
The term platform has multiple meanings in web application circles, depending on how you slice the computing world. Typically, a platform denotes any hardware and/or software system that forms the basis for further product development. Operating system developers regard each microprocessor family as a platform (Pentium, PowerPC, or SPARC CPUs, for example); desktop computer application developers treat the operating system as the platform (Win16, Windows 95/NT, MacOS8, Unix, Linux, and the rest); peripherals makers perceive a combination of hardware and operating system as the platform (for example, a Wintel machine or a Macintosh).
The de facto acceptance of the web protocols, such as HTTP, means that a web application developer doesn't have to worry about the underlying network transport protocols that are being used. Theoretically, all client computers equipped with browsers that support the web protocols—regardless of the operating system or CPU—should be treated as a single platform. The real world, however, doesn't work that way.
Today's crop of web browsers are far more than data readers. Each one includes a highly customized content rendering engine, a scripting language interpreter, a link to a custom Java virtual machine, security access mechanisms, and connections to related software modules. The instant you decide to author content that will be displayed in a web browser, you must concern yourself with the capabilities built into each browser. Despite a certain level of interoperability due to industry-wide standards, you must treat each major browser brand as a distinct development platform. Writing content to the scripting API or HTML tags known to be supported by one browser does not guarantee support in the other browser.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Is a Platform?
The term platform has multiple meanings in web application circles, depending on how you slice the computing world. Typically, a platform denotes any hardware and/or software system that forms the basis for further product development. Operating system developers regard each microprocessor family as a platform (Pentium, PowerPC, or SPARC CPUs, for example); desktop computer application developers treat the operating system as the platform (Win16, Windows 95/NT, MacOS8, Unix, Linux, and the rest); peripherals makers perceive a combination of hardware and operating system as the platform (for example, a Wintel machine or a Macintosh).
The de facto acceptance of the web protocols, such as HTTP, means that a web application developer doesn't have to worry about the underlying network transport protocols that are being used. Theoretically, all client computers equipped with browsers that support the web protocols—regardless of the operating system or CPU—should be treated as a single platform. The real world, however, doesn't work that way.
Today's crop of web browsers are far more than data readers. Each one includes a highly customized content rendering engine, a scripting language interpreter, a link to a custom Java virtual machine, security access mechanisms, and connections to related software modules. The instant you decide to author content that will be displayed in a web browser, you must concern yourself with the capabilities built into each browser. Despite a certain level of interoperability due to industry-wide standards, you must treat each major browser brand as a distinct development platform. Writing content to the scripting API or HTML tags known to be supported by one browser does not guarantee support in the other browser.
If you are creating content, you must also be aware of differences in the way each browser has been tailored to each operating system. For example, even though the HTML code for embedding a clickable button inside a form is the same for both Navigator and Internet Explorer, the look of that button is vastly different when rendered in Windows, Macintosh, and Unix versions of either browser. That's because the browser makers have appropriately observed the traditions of the user interface look and feel for each operating system. Thus, a form whose elements are neatly laid out to fit inside a window or frame of a fixed size in Windows may be aligned in a completely unacceptable way when displayed in the same browser on a Macintosh or a Unix system.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Navigator 4 DHTML
As early as Navigator 2, JavaScript offered the possibility of altering the content being delivered to a browser as a page loaded. It was Navigator 3, however, that showed the first glimpse of what Dynamic HTML could be. This browser implemented the IMG HTML element as a document object whose SRC attribute could be changed on the fly to load an entirely different image file into the space reserved by the <IMG> tag. In DHTML parlance, this is known as a replaced element because it is rendered as an inline element (capable of flowing in the middle of a text line), yet its content can be replaced afterward. The most common application of this replacement feature is the mouse rollover, in which an image is replaced by a highlighted version of that image whenever the user positions the cursor atop the image. If you surround the <IMG> tag with a link (<A>) tag, you can use the link's mouse event handlers to set the image object's source file when the cursor rolls atop the image and when it rolls away from the image:
<A HREF="someURL.html" 
    onMouseOver="document.images['logo'].src = 'images/logoHOT.jpg'" 
    onMouseOut="document.images['logo'].src = 'images/logoNORMAL.jpg'">
<IMG NAME="logo" SRC="images/logoNORMAL.jpg" HEIGHT=40 WIDTH=80>
</A>
At the time, this capability was a breakthrough that allowed dynamic content without the delay of loading a Java applet or rich media for a plug-in. Navigator 3 even allowed JavaScript to pre-cache all images on a page during the initial page download, so that the first image transition was instantaneous.
A glaring limitation of this scheme, however, hindered some designs. The size of the image area was fixed by the IMG element's HEIGHT and WIDTH attributes when the page loaded. All other images assigned to that object had to be the same size or risk being scaled to fit. While rarely a problem for mouse rollovers, the lack of size flexibility got in the way of more grandiose plans.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Internet Explorer 4 DHTML
While Internet Explorer 3 (for Windows) did not even allow for swapping of images after a document loaded, IE 4 provides substantial facilities for dynamically modifying the content of a page after it has loaded. In addition, you can dynamically create content during loading with the help of VBScript or JScript, just as you could in IE 3. IE 4 exposes virtually every element defined by HTML in a document to the scripting language of your choice.
Some CSS functionality was introduced in IE 3, but almost every aspect of the W3C recommendation for CSS1 is implemented in IE 4. Only a few CSS1 attributes, such as word-spacing and white-space, are missing from the IE 4 implementation.
In addition to supporting the specifications of the working draft of CSS-Positioning that existed at the time of IE 4's release in 1997, the browser also allows you to apply CSS-P attributes to individual HTML elements—including those that are not containers. Therefore, you can assign a specific position and visibility to, say, an image, even when it is not surrounded by a container tag such as <DIV> or <SPAN>:
<IMG SRC="myFace.jpg" HEIGHT=60 WIDTH=40 
STYLE="position:absolute; left:200; top:100">
Of course, you can also assign positioning attributes to containers, if you prefer.
IE 4's rendering engine is designed in such a way that it can respond very quickly to changes in content. The browser's document object model provides access to virtually every kind of content on a page for modification after the document has loaded. For example, a script can alter the text of a specific <H1> header or the size of an image at any time. The rendering engine instantaneously reflows the page to accommodate the newly sized content. With each HTML element exposed to scripting as an object, most properties can be changed on the fly. The model even accommodates changing the HTML associated with an element. For example, you can demote an
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cross-Platform Strategies
If your DHTML application must run on both Netscape and Microsoft browsers, you have a choice of several deployment strategies to pursue: page branching, internal branching, common denominator design, and custom API development. In all likelihood, your application will employ a combination of these techniques to get the same (or nearly the same) results on both platforms. No matter how you go about it, you must know the capabilities of each browser to provide equivalent experiences for users of both browsers. The rest of this book is designed to help you understand the capabilities of each browser, so the material in this section is mostly about the different strategies you can use.
Web pages that use absolute-positioned elements degrade poorly when displayed in older browsers. The positioned elements do not appear where their attributes call for, and, even worse, the elements render themselves from top to bottom in the browser window, in the order in which they appear in the HTML file. Also, any elements that are to be hidden when the page loads appear in the older browsers in their source code order. To prevent users of older browsers from seeing visual gibberish, you should have a plan in place to direct users of non-DHTML-capable browsers to pages containing less flashy content or instructions on how to view your fancy pages. A server-side CGI program can perform this redirection by checking the USER_AGENT environment variable sent by the client at connect-time and redirecting different HTML content to each browser brand or version.
Alternatively, you can do the same branching strictly via client-side scripting. Depending on the amount of granularity you wish to establish for different browser brands and versions at your site, you have many branching techniques to choose from. All these techniques are based on a predominantly blank page that has some scripted intelligence behind it to automatically handle JavaScript-enabled browsers. Any script-enabled browser can execute a script that looks into the visitor's browser version and loads the appropriate starter page for that user. Example 2.1 shows one example of how such a page accommodates both scripted and unscripted browsers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cross-Platform Expectations
Before undertaking cross-platform DHTML development, be sure you understand that the features you can exploit in both browsers—regardless of the techniques you use—are limited to comparable feature sets within the realms of style sheets, positionable elements, event models, object models, and downloadable fonts. Dynamic content on a small scale is also a cross-platform possibility, but the instantaneous reflowing of modified content, display filters, and transitions that are available in Internet Explorer 4 have no parallels in Navigator 4.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: Adding Style Sheets to Documents
Like their counterparts in word processing and desktop publishing programs, HTML style sheets are supposed to simplify the deployment of fine-tuned formatting associated with content. Instead of surrounding every H1 element in a document with <FONT> tags to make all of those headings the same color, you can use a one-line style definition in a style sheet to assign a color to every instance of the H1 element on the page. Of course, now that style sheets make it easier to specify colors, margins, borders, and unusual element alignments, you are probably adding more HTML elements to your documents. So your documents may not be any smaller, but they should be more aesthetically pleasing, or at least closer to what you might design in a desktop publishing program.
In order to successfully incorporate style sheets into HTML documents, you may have to reexamine your current tagging practices. How much you'll have to change your ways depends on how and when you learned HTML in the first place. Over the years, popular browsers have generally been accommodating with regard to—how shall I say it—less-than-perfect HTML. Consider the <P> tag, which has long been regarded as a single tag that separates paragraphs with a wider line space than the <BR> line break tag. HTML standards even encourage this start-tag-only thinking by making some end tags optional. You can define an entire row of table cells without once specifying a </TD> or </TR> tag: the browser automatically closes a tag pair when it encounters a logical start tag for, say, the next table cell or row.
The "new thinking" that you may have to adopt is triggered by an important fact: style sheets, and the browser object models that work with them, are largely container oriented. With rare exception (the <BR> tag is one), an element in a document should be treated as a container whose territory is bounded by its start and end tags (even if the end tag is optional). This container territory does not always translate to space on the page, but rather applies to the structure of the HTML source code. To see how "HTML-think" has changed, let's look at a progression of simple HTML pages. Here's a page that might have been excerpted from a tutorial for HTML Version 2:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Rethinking HTML Structures
In order to successfully incorporate style sheets into HTML documents, you may have to reexamine your current tagging practices. How much you'll have to change your ways depends on how and when you learned HTML in the first place. Over the years, popular browsers have generally been accommodating with regard to—how shall I say it—less-than-perfect HTML. Consider the <P> tag, which has long been regarded as a single tag that separates paragraphs with a wider line space than the <BR> line break tag. HTML standards even encourage this start-tag-only thinking by making some end tags optional. You can define an entire row of table cells without once specifying a </TD> or </TR> tag: the browser automatically closes a tag pair when it encounters a logical start tag for, say, the next table cell or row.
The "new thinking" that you may have to adopt is triggered by an important fact: style sheets, and the browser object models that work with them, are largely container oriented. With rare exception (the <BR> tag is one), an element in a document should be treated as a container whose territory is bounded by its start and end tags (even if the end tag is optional). This container territory does not always translate to space on the page, but rather applies to the structure of the HTML source code. To see how "HTML-think" has changed, let's look at a progression of simple HTML pages. Here's a page that might have been excerpted from a tutorial for HTML Version 2:
<HTML>
<HEAD>
<TITLE>Welcome to HypeCo</TITLE>
</HEAD>
<BODY>
<H1>Welcome to HypeCo's Home Page</H1>
We're glad you're here.
<P>
You can find details of all of HypeCo's latest products and special offers. 
Our goal is to provide the highest quality products and the best customer 
service in the industry.
<P>
</BODY>
</HTML>
While the preceding HTML produces a perfectly fine, if boring, page, a modern browser does not have enough information from the tags to turn the content below the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Block-Level Elements
If you are a style sheet coder, you must be aware of the element containment dictated by HTML tags. If you are a page designer, however, you need to understand an entirely different kind of containment structure: block-level elements. A block-level element is a self-contained unit of content that normally begins at the starting margin of one line and ends in a way that forces the next bit of content to appear on a new line following the block. Each of the heading tags (H1, H2, etc.) is a block-level element because it stands alone on a page (unless you use DHTML positioning tricks to overlay other elements). Other common block-level elements are P, UL, OL, and LI.
A CSS-enabled browser automatically defines a set of physical features to every block-level element. By default, the values for all these features are set to zero or none, so that they don't appear or occupy space on the page when you use simple HTML tags without style sheets. But one of the purposes of style sheets is to let you modify the values of those features to create graphical borders, adjust margin spacing, and insert padding between the content and border. In fact, those three terms—border, margin, and padding—account for about half the style sheet attributes implemented in the Version 4 browsers.
You can think of the content and features of a block-level element as a box. To help you visualize the role and relative position of the features of a block-level element, Figure 3.2 shows a schematic diagram of a generic chunk of block-level content (imagine it's a paragraph, if that helps), where the margin, border, and padding are indicated in relation to the content. The width and height of the content are the same, regardless of extra stuff being tacked on outside of the content. Each of the surrounding features—padding, borders, and margins—can occupy space based on its corresponding dimensions. The width and height of the entire box is the sum of the element content, plus padding, borders, and margins. If you don't assign any values to those features, their dimensions are zero and, therefore, they contribute nothing to the dimensions of the box. In other words, without any padding, borders, or margins, the content and box dimensions are identical. With style sheets, you can assign values to your choice of edges (top, right, bottom, or left) for any feature.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Two Types of Containment
If you have worked with JavaScript and the scriptable document object models inside Navigator and Internet Explorer, you are aware that scriptable document objects have a containment hierarchy of their own—an object containment hierarchy. The window object, which represents the content area of a browser window or frame, is at the top of the hierarchy. The window object contains objects such as the history, location, and document objects. The document object contains objects such as images and forms, and, among the most deeply nested objects, the form object contains form elements, such as text fields and radio buttons.
Document object containment is important in JavaScript because the hierarchy defines how you refer to objects and their methods and properties in your scripts. References usually start with the outermost element and work their way inward, using the JavaScript dot syntax to delimit each object. For example, here's how to reference the content of a text field (the value property) named zipCode inside a form named userInfo:
window.document.userInfo.zipCode.value
Unlike most object-oriented worlds (such as Java), the object-based world of scriptable browsers does not strictly adhere to the notion of parents and children. In fact, except for the relationship between a frameset document and the frames it creates, the word "parent" is not part of the object containment vocabulary. Document objects do not inherit properties or methods of objects higher in the containment hierarchy.
In contrast to this structure, styles adhere more closely to the element containment as defined by the tag geography of a document. In this context, you do see frequent references to parents and children. That's because an element can inherit a style assigned to another element higher in the element containment hierarchy.
All HTML document elements belong to the document's inheritance chain. The root of that chain is the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
CSS Platforms
Starting with Cascading Style Sheet Level 1, you can use an attribute of the STYLE element to specify the syntax you are using to define style sheets. The value of the TYPE attribute is in the form of a content-type declaration; it defines the syntax used to assign style attributes. The formal CSS recommendation by the W3C promotes a syntax of content type text/css . This TYPE attribute is not required in today's leading browsers, but the CSS recommendation does not believe that there should be a default type. Therefore, I strongly recommend specifying the TYPE attribute for all style sheets, in case some other user agent (an HTML-empowered email reader, for example) should implement a strict interpretation of the CSS standard in the future. A STYLE element that relies on the CSS syntax should look like the following:
<STYLE TYPE="text/css">
...
</STYLE>
Internet Explorer 4 and Navigator 4 both recognize the text/css type of CSS syntax. Navigator 4 also includes an alternative syntax that follows the JavaScript object reference format. This alternate type, text/javascript, provides Java-Script equivalents for most of the style attributes and structures provided by the text/css syntax. The Navigator implementation also includes the power to use JavaScript statements and constructions inside <STYLE> tags to assist in defining styles based on client- or user-specific settings (as demonstrated later in this chapter). In other words, the implementation of style sheets in Navigator 4 is largely CSS compatible, and style sheets can be specified using either CSS or JavaScript syntax.
In the early days of Navigator 4 (prerelease and early final versions), Netscape referred to style sheets of type text/javascript with names such as JavaScript Style Sheets (JSS or JSSS, depending on whom you talk to) or JavaScript-Accessible Style Sheets. The official terminology changes with the wind, but these earlier names are no longer part of the Netscape marketing vocabulary. At last reading, the company referred to this technology as "accessing style sheet properties from JavaScript via the Document Object Model"—even though the formal Document Object Model standard was far from complete at the time.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Of Style Sheets, Elements, Attributes, and Values
Regardless of the syntax you use to define a style sheet, the basic concepts are the same. A style sheet is a collection of one or more rules. Each rule has two parts to it:
  • One or more elements (or groups of elements) that are having style sheets defined for them
  • One or more style sheet attributes that apply to the element(s)
In other words, each rule defines a particular look and feel and the item(s) in the document that are to be governed by that look and feel.
A style attribute is the name of a (usually) visible property of a piece of content on the page. An attribute such as foreground color can apply to any element because that color can be applied to foreground content, such as text. Some attributes, such as borders and margins, can apply only to elements rendered as blocks on the page—they have a clear beginning and ending in both the HTML source code and in the layout. Details on all the CSS style sheet attributes can be found in Chapter 10, but Table 3.1 shows a summary of CSS1 attributes implemented in both Internet Explorer 4 and Navigator 4 (in both CSS and JavaScript syntax). Each browser also defines other style attributes that are noted in Chapter 10.
Table 3.1: Summary of CSS1 Style Sheet Attributes in Version 4 Browsers
Attribute Name—CSS Syntax (IE 4 and NN 4)
Attribute Name—JavaScript Syntax (NN 4)
Box Properties
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Embedding Style Sheets
If you want to develop style sheet-enhanced pages that work in both Internet Explorer and Navigator, you should use the CSS syntax. In the next few sections, all of examples I present are going to use the CSS syntax, since it works in both browsers. Later, I'll discuss the Navigator-specific JavaScript syntax for style sheets.
Style sheets can be added directly to a document or imported from one or more external files. In-document and external style sheets coexist well in the same document; you can have as many of each type as your page design requires.
There are two ways to embed CSS information directly in an HTML document: using the <STYLE> tag pair or using STYLE attributes of HTML tags. For ease of maintenance and consistency throughout a document, I recommend using a <STYLE> tag inside the HEAD section of the document. But you can also include STYLE attributes directly inside the tag for almost any HTML element.

Section 3.6.1.1: The <STYLE> tag

It is convenient to define style sheet rules between <STYLE> and </STYLE> tags. The collection of rules within these tags is the classic instance of a CSS style sheet. Because the elements to which you bind style declarations can appear early in the body of the document (and may be bound to the BODY element itself), you should use the <STYLE> tag in the HEAD section of your document. This guarantees that the style sheet is loaded and in effect before any elements of the document are rendered. Include the TYPE attribute in the opening tag, as in:
<STYLE TYPE="text/css">
    style sheet rule(s) here
</STYLE>
Some older browsers ignore the start and end tags and attempt to render the contents as if they were part of the document body. If you fear that this will affect users of your pages, you can surround the statements inside the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Subgroup Selectors
While a selector for a style sheet rule is most often an HTML element name, that scenario is not flexible enough for more complex documents. Consider the following possibilities:
  • You want certain paragraphs scattered throughout the document to be set apart from running text by having wider left and right margins.
  • You want all H2 elements in the document but one to be set to the color red; the exception must be blue.
  • In a three-level ordered list (OL) group, you want to assign different font sizes to each level.
Each of these possibilities calls for a different way of creating a new selector group or specifying an exception to the regular selectors. In an effort to distance design from content, CSS style sheets provide three ways of creating subgroups that can handle almost every design possibility:
  • Class selectors
  • ID selectors
  • Contextual selectors
Using these subgroup selectors requires special ways of defining selectors in style sheet rules. These selectors also require the addition of attributes to the HTML tags they apply to in the document.
A class selector is an identifier you can use to assign a style to a subset of elements in a document. To apply a class selector, you first invent an identifier for the class name. To allow for the potential scripting of class names, it is wise to adhere to the rules of JavaScript identifiers when devising class names. A Java-Script identifier is a one-word name (i.e., no spaces) that can include numerals, letters, and limited punctuation (such as the underscore character). Also, the first character of an identifier cannot be a numeral. The CSS2 guidelines for selector identifiers are less stringent: you can embed hyphens, Unicode characters above 160, and escaped characters (characters that begin with a backslash character) in an identifier, but the name must not begin with a numeral or hyphen. If you are now or may eventually script class selectors, follow the JavaScript rules instead of the more liberal CSS2 rules.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Attribute Selector Futures: CSS2
Navigator 4 and Internet Explorer 4 implement the individual, class, ID, and contextual selector schemes described in the previous sections. The newer CSS2 specification makes further enhancements to the way selectors can be specified in style sheet rules. Some of these recommendations may find their way into future versions of the browsers (IE 4 already uses a few of them) or other implementations of style sheets (such as in XML-enabled applications). These items are noted here briefly to offer a preview of what you might expect in the next generation of DHTML-capable browsers. However, since specifications like CSS do not insist on 100% compliance (some items are optional), don't be surprised if some of the items described in this section do not appear in the next version of your browser.
The original idea for pseudo-elements and pseudo-classes was defined as part of the CSS1 recommendation; these selectors have been expanded in CSS2. A fine line distinguishes these two concepts, but they do share one important factor: there are no direct HTML tag equivalents for the elements or classes described by these selectors. Therefore, you must imagine how the selectors will affect the real tags in your document.

Section 3.8.1.1: Using pseudo-elements

A pseudo-element is a well-defined chunk of content in an HTML element. Two pseudo-elements specified in the CSS1 recommendation point to the first letter and the first line of a paragraph. The elements are named :first-letter and :first-line, respectively. It is up to the browser to figure out where, for example, the first line ends (based on the content and window width) and apply the style only to the content in that line. If the browser is told to format the :first-letter pseudo-element with a drop cap, the browser must also take care of rendering the rest of the text in the paragraph so that it wraps around the drop cap.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
JavaScript Style Sheet Syntax
So far throughout this chapter, all style sheet examples have used the CSS syntax promoted in the W3C recommendations and implemented to varying degrees in both Navigator 4 and Internet Explorer 4. In this section, we discuss Netscape's alternative syntax for specifying style sheets. This syntax follows the rules of the JavaScript (and, by extension, ECMAScript) language, but the object model is unique to Navigator 4. Unless you exercise browser branching safeguards, you will encounter script errors if you attempt to load documents equipped with this style sheet syntax into Internet Explorer 4. It's important to emphasize that this is not an alternate style sheet mechanism; rather, it is just another way to program CSS style sheets. The advantage of this syntax is that you gain the power of using other JavaScript statements inside <STYLE> tags to create, for example, algorithmically derived values for style sheet rules.
As you may have noticed in Table 3.1, not every CSS attribute implemented in Navigator 4 has a JavaScript equivalent. The most common attributes are accounted for, but some design choices, such as setting independent colors for border sides, aren't available in Navigator 4—in JavaScript or CSS syntax.
JavaScript syntax simplifies assigning values to style attributes and then assigning those attributes to HTML elements, in that you don't have to learn the CSS syntax. Each statement in a JavaScript style sheet is a property assignment statement. The object reference on the left side of the statement is an element type, class, or ID. These objects all have style properties to which you can assign values.
To demonstrate the difference in syntax, the next listing is a duplicate of one earlier in the chapter that showed a simple setting of two style rules in CSS syntax:
<HTML>
<HEAD>
<STYLE TYPE="text/css">
    H1 {color:red; text-transform:capitalize}
    P {color:blue}
</STYLE>
</HEAD>
<BODY>
<H1>Some heading</H1>
<P>Some paragraph text.</P>
</BODY>
</HTML>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cascade Precedence Rules
By now it should be clear that there are many ways styles can be applied to an element—from an external style sheet file, from a <STYLE> tag set, and from a STYLE attribute in a tag—and there is the possibility that multiple style rules can easily apply to the same element in a document (intentionally or not). To deal with these issues, the CSS recommendation had to devise a set of rules for resolving conflicts among overlapping rules. These rules are intended primarily for the browser (and other user agent) makers, but if you are designing complex style sheets or are seeing unexpected results in a complex document, you need to be aware of how the browser resolves these conflicts for you.
Conflict resolution is mostly a matter of assigning a relative weight to every rule that applies to a particular element. Rules with the most weight are the ones that most specifically target the element. At the lightweight end of the spectrum is the "nonrule," or default style setting for the document, generally governed by the browser's internal design and sometimes influenced by preference settings (e.g., the base font size for text content). Such a "nonrule" may actually apply directly only to a high-level object, such as the BODY element; only by way of inheritance does the default rule apply to some element buried within the content. At the heavyweight end of the spectrum is the style rule that is targeted specifically at a particular element. This may be by way of an ID selector or the ultimate in specificity: a STYLE attribute inside the tag. No rule can override an embedded STYLE attribute.
Between those two extremes are dozens of potential conflicts that depend on the way style sheets are defined for the document. Before rendering any style-sheet-capable element, the browser uses the following decision path to determine how that element should be rendered:
  1. Scan the document for any style declarations that have a selector that matches the element. If the element is not selected by any rules, short-circuit the rest of the decision path and render the element according to the browser's current settings.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cross-Platform Style Differences
Despite the commonality that CSS brings to Navigator and Internet Explorer, there is no guarantee that the visual representation of a particular style will be the same in both browsers. Differences can be attributed to browser bugs, varying interpretations of the standard, and disagreements in design philosophies. Differences can also accrue even among different operating system versions of the same browser.
To demonstrate this point, Figures Figure 3.4, 3-5, and 3-6 show three different renditions of the same CSS-enhanced page (Example 3.4) in Internet Explorer 4 for Windows 95, Navigator 4 for Windows 95, and Navigator 4 for the Macintosh. All browser windows were sized to fill a 640-by-480 monitor, minus the Windows 95 Taskbar and Macintosh menu bar.
Figure 3.4: Example 3.4 loaded into Internet Explorer 4 for Windows 95
Figure 3.5: Example 3.4 loaded into Navigator 4 for Windows 95
Figure 3.6: Example 3.4 loaded into Navigator 4 for the Macintosh
Notice how each browser shows a vastly different quantity of the document, even though a specific font point size is assigned for all paragraph elements. Next, check out how Internet Explorer and Navigator treat default padding between a border and its content: Navigator automatically builds in a three-pixel padding (which cannot be overridden) to keep content away from a border. Another point that may not be clearly visible from the figures is that the precise shades and shadowing of the border are different between the two browser brands (detailed galleries are available in the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 4: Adding Dynamic Positioning to Documents
Cascading style sheets, as described in Chapter 3, are primarily concerned with how content looks on the screen (or how it looks on a page printed from the screen). An extension to CSS, called CSS-Positioning (or CSS-P), is primarily concerned with where content appears on the page. CSS-P is blended with regular CSS in the CSS2 specification, but because the Version 4 browsers were designed while positioning was a separate standards effort, I use the CSS-P term frequently.
The CSS-P recommendation from the W3C focuses on the HTML code that authors put into documents to govern the position of elements on the page when the browser-controlled flow of content just isn't good enough. To accomplish element positioning, a browser must be able to treat positionable elements as layers that can be dropped anywhere on the page, even overlapping other fixed or positionable elements—something that normal HTML rendering scrupulously avoids.
The notion of layering adds a third dimension to a page, even if a video monitor (or a printed page) is undoubtedly a two-dimensional realm. That third dimension—the layering of elements—is of concern to you as the author of positionable content, but is probably of no concern to the page's human viewer.
While the CSS-P recommendation offers a cross-platform way to lay out positionable elements, the browsers have extended the idea by turning positionable elements into scriptable objects whose properties can be changed in response to user action. Now you have the opportunity to create some very interactive content: content that flies around the page, hides and shows itself at will, centers itself horizontally and vertically in the currently sized browser window, and even lets itself be dragged around the page by the user.
The implementations of positionable elements in Navigator 4 and Internet Explorer 4 are perhaps the most divergent parts of DHTML to grace both browsers. If you have the luxury of designing an application for only one browser platform, you can focus on the implementation for that browser to the exclusion of the other browser's idiosyncrasies. Successful cross-platform development, however, requires knowledge of both browsers' object models (at least as they relate to positionable elements) and the range of DHTML authoring capabilities in both browsers. As you will see in this chapter, there is a common denominator of functionality, but it is often up to you to raise the level of commonality in order to get a highly interactive page to work identically in both browsers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating Positionable Elements
Content preview·