Working with DOM (II)
Contents
DYnamic Content
Dynamic content features
Changing HTML Content
Adding Document Content
Case Study: Building a Table of Contents
Using the TextRange Object
Overview
What Do I Do with a TextRange Object?
Getting the Content of a TextRange
Comparing Ranges
Commands
Finding Text in the Document
Positioning
What Is Positioning?
Absolute Positioning
Relative Positioning
Positioning Considerations
Combining Dynamic Positioning Techniques
Controlling Content Visibility
Clipping Regions and Overflow
Z-Index Ordering
Element Visibility
Filters and Transitions
Creating Multimedia Effects
What Are HTML Controls?
Defining Visual Filters
Scripting Filters
The Filter String
Migrating from OBJECT-based Filters
Filter Design Considerations
Transitions
Interpage Transitions
Transition Syntax
Transitions Reference
Transition Design Considerations
Font Embedding
Embedded Font Technology
Different Levels of Font Embedding
Limitations in Internet Explorer 4.0
Internet Explorer 4.0 Security Alert
Using Microsoft WEFT
WEFT Style Code
Cascading Style Sheet Files
Examples
Example # 1 -
Example # 2 -
Example # 3 -
Example # 4 -
Example # 5 -
Example # 6 -
Example # 7 -
Example # 8 -
Example # 9 -
Example # 10 -
Example # 11 -
Dynamic Content
Before Microsoft Internet Explorer 4.0, once a Web page was loaded into a user's browser, changing the information displayed on the page required another round-trip to the server. The user interacted with the page (submitted a form, or clicked a link to another page), and the server delivered a new page to the client. Any customization of the information (such as building the page on the fly from a template) required that the server spend additional time processing a page request. Furthermore, the only way to maintain the context for the page's content was to use frame sets, where one frame's content stays constant and another frame changes its content based on the user's activity on the initial page. Dynamic content is all about changing the content of the HTML document-inserting and deleting elements or the contents of an element before or after the document has been loaded.
Dynamic content features
Internet Explorer 4.0 gives you a rich set of properties and methods to dynamically construct and alter Web pages on the fly. For example, a script can insert a list of section titles at the beginning of the document, or replace that list with a list of links to the actual sections in the document.
Changing HTML Content
Internet Explorer 4.0 provides a set of properties and methods on each element that are designed to make it quite simple to change the document. There are four properties that provide the ability to see what's inside an element on the page and replace that content with new information: innerText, outerText, innerHTML, and outerHTML.
Assigning new text (also called a "string") to one of these properties replaces the contents of the element, including any elements contained by that element, with the new string. Consider the following HTML for an H1 heading.
<H1 id=myH1>Dynamic Content is Very Cool!</H1>
The content of the H1 can be changed with the innerText property.
document.all.myH1.innerText = "DHTML is Very Cool"
The H1 element remains in the document, while the content of the H1 changes to contain the new string "DHTML is Very Cool". The string assigned to innerText renders any HTML tags as text, and does not process the HTML. To insert HTML code into the contents of another element, you must use the innerHTML property.
document.all.myH1.innerHTML = "DHTML is <I>Very</I> Cool!"
The new string replaces the original content of the H1, and the word "Very" appears in italic.
The outerText and outerHTML properties represent the element itself, as well as the contents of the element. Assuming that the preceding example is contained by a BODY element, using an outerText property on the H1 replaces the entire element with the string attached. The following script causes the H1 to go away entirely, and the text string appears where the element was in the flow of the BODY 's content.
document.all.myspan.outerText = "DHTML is VERY Cool!"
The outerHTML property replaces the element with rich HTML. Much like the example above where HTML was inserted in the H1, using the outerHTML property will do the same, except the H1 would also be removed.
document.all.myH1.outerHTML = "<SPAN STYLE='height:0;width:200;
FILTER:Shadow(color=#00FF00)'>
RICH HTML</SPAN>";
Adding Document Content
The properties described above replace the entire contents of an element with a new string. What if you only want to insert new text or HTML and don't want to change what is already in the document? There are two helper methods on most elements that help you do just this.
These methods, insertAdjacentHTML and insertAdjacentText, place the new content at the beginning or end of the element, leaving the existing content intact. These methods all take a parameter that indicates one of four possible places the new content can be inserted with regard to the element: BeforeBegin, AfterBegin, BeforeEnd, and AfterEnd.
The following example appends a new paragraph to the end of the document when it loads.
<HTML>
<HEAD>
<TITLE>Dynamic Content: Inserting Elements</TITLE>
<SCRIPT LANGUAGE="JScript">
function insertPara()
</SCRIPT>
</HEAD>
<BODY onload="insertPara()">
<P>This is a <B>very</B> short document.</P>
</BODY>
</HTML>
Example # 1 -
Case Study: Building a Table of Contents
Building a table of contents is a good example of dynamic content at its best. By using a relatively small amount of script, you can automatically generate a detailed list of the contents of any document.
This example consists of three functions: buildTOC, setAnchor, and setLink. The buildTOC function creates the table of contents, calling the other two functions to apply anchors and insert the links. The example depends on the document having an element, such as DIV or P, that has the identifier "MyTOC". The setLink function inserts the links there. To build the table successfully, buildTOC cannot be called until the document is fully loaded.
Once buildTOC is called, it uses the all collection to check each element to see whether it is a header element: H1, H2, H3, or H4. It starts the search at the first element after the BODY element since no links are possible before this. When it finds a header, it sets the "level" variable and calls the setAnchor and setLink functions.
function buildTOC()
if (level!=-1)
}
Notice how the variable "i" is updated after the call to setAnchor and setLink. These functions insert new elements into the document, causing the all collection to be immediately updated and requiring a new index value for the heading. The setAnchor function inserts one element before the heading, so the index is increased by one; the setLink function inserts two elements at the top of the document, so the index is increased by two.
The setAnchor function adds an A element to the document, inserting the start and ends tags for this element immediately before and after the header tag, and setting the NAME= attribute of the new element to be equal to the "id" parameter passed to the function.
function setAnchor(el, id)
The setLink function adds another A element to the document. This time the element is a link to the heading that setAnchor just created an anchor for. The HREF= attribute is set to the same "id" value as was set in the matching anchor. Notice that the setLink function places the link just before the end of the element having the identifier "MyTOC", separating it from the previous link with a BR element and inserting zero or more nonbreaking spaces for a very simple way to indicate the heading level.
function setLink(el, level, id)
There are a few things to keep in mind when you are dynamically changing content in your Web page.
Can't modify the content until after the document has been loaded: Keep in mind that you cannot assign a string to these properties until the document has been completely loaded, that is, until the onload event occurs. If you attempt to do so before loading, an error occurs.
Be careful! When you add an element to a document, the all and other element collections are automatically updated to reflect the change. This also affects the value of the sourceIndex for elements that follow the new elements. If you have saved the index value of an element, be careful to update that value or retrieve a new value whenever you add or delete elements in a document.
Can't put invalid HTML in the document: You cannot assign a string to innerHTML or outerHTML that contains invalid HTML. For example, trying to replace the content of the P element with another P will fail. A P element can only contain text and inline elements. However, replacing the entire P element with another P would work just fine.
Which Elements Will This Work For? Here are a few guidelines for which elements you can expect these properties and methods to work:
Only elements that appear in the BODY of the document can be changed with these properties. You can replace the contents of the BODY, but you can't replace the BODY itself.
This should be obvious, but deserves mention anyway: you can't replace the contents of an element where the element type doesn't have any contents like the replaced elements, INPUT and IMG.
The contents of a TD can be changed (innerText and innerHTML) and the TABLE element itself can be replaced (outerText and outerHTML), but no other table elements and their contents can be changed with these properties.
Using the TextRange Object
Most users will only want to use the innerText/innerHTML and outerText/outerHTML properties and methods discussed previously. However, there is some more advanced text manipulation that can be done using a "text range" object. The TextRange object can be used to:
Locate the text for a given element or a given point.
Search for words and characters in the text of the document.
Move through the text in logical units.
Provide read/write access to the plain text and the HTMLText in the document.
Overview of the TextRange Object
Text range objects are an advanced feature of Dynamic HTML that you can use to carry out useful tasks related to dynamic content, such as searching for and selecting text. Text ranges let you selectively pick out characters, words, and sentences from a document. The TextRange object is an abstract object that creates a start and end position over the stream of text that would appear in the HTML document. Consider the following simple HTML document:
<HTML>
<BODY>
<H1>Welcome</H1>
<CENTER><H2>Overview<H2></CENTER>
<P>Be sure to <B>Refresh</B> this page.</P>
</BODY>
</HTML>
Example # 2 -
In this document, creating a text range over the BODY would position the start at the beginning of the textual content of the BODY, and the end at the end of the textual content of the BODY. This text range would contain the plain text "Welcome Overview Be Sure to Refresh this page."
What Do I Do with a TextRange Object?
There are two parts to manipulating text with a TextRange object. The first is to create a text range so that the start and end positions encompass the desired text. The next step is to apply a method to the text range, or make a copy of the text to be used elsewhere in the document. Once the text range is positioned, you can search for text, select the text, and make a copy of the text and use it elsewhere in your document.
Positioning the TextRange Object
Each text range has a start and an end position defining the scope of the text that is encompassed by the TextRange object. When you create a new text range, the start and end positions encompass the entire content by default. Use methods such as move, moveStart, and moveEnd to change the scope of the text range.
Other methods can position the TextRange object with respect to a particular element, or a point on the page. For example, moveToElementText positions the text range so that it encompasses the text contained by the given element. moveToPoint positions the text range at a given point where the user clicked a mouse button. The x and y positions of the user's click are known by the window.event object and can be used to position the range over a given point. From this collapsed point, the range can then be expanded to encompass a word, sentence, or a whole textEdit (the entire possible TextRange object).
<HTML><HEAD><TITLE>moveToPoint Example</TITLE>
<script>
function selectMe()
</script>
</HEAD>
<BODY>
<H1 id=myH1 onclick=selectMe()>Click on a word and it will highlight </H1>
</BODY>
</HTML>
Example # 3 -
You create a TextRange object by applying the createTextRange method to a BODY, TEXTAREA, or BUTTON element. You can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange.
Creating a TextRange object on the body will not include the content inside a TEXTAREA or BUTTON. Conversely, you cannot change the start or end position of a text range over the TEXTAREA or BUTTON to move outside the scope of these particular elements. Use the properties provided on each element, isTextEdit and parentTextEdit, to walk the hierarchy. If the document above contained a TEXTAREA, a createTextRange on the body object would not find the position where the user actually clicked. The following reworks the above example to handle this case.
<HTML><HEAD><TITLE>moveToPoint Example</TITLE>
<script for=document event=onclick>
var r
if(window.event.srcElement.isTextEdit) else
r.moveToPoint(window.event.x, window.event.y);
r.expand("word");
r.select();
</script>
</HEAD>
<BODY>
<H1 id=myH1>Click on a word and it will highlight</H1>
<TEXTAREA>There's text in this element too that you could click on</TEXTAREA>
</BODY>
</HTML>
Example # 4 -
Getting the Content of a TextRange
The content of a TextRange object can be viewed with the text or HTMLtext property on the TextRange object. The text property is a read/write property that is similar to the innerText properties on the element objects, only this replaces the text encompassed by a TextRange object.
HTMLtext is a read-only property that lets you examine the HTML that is contained within the start and end points of the TextRange object. To add rich HTML content to the text range, use the pasteHTML method. Although you can paste any HTML text that you want into a text range, the pasteHTML method does not preserve the hierarchy of the document, as do the innerHTML and outerHTML properties. Although pasteHTML won't fail if you paste invalid or inappropriate tags into the range, the resulting document may not look or behave the way you expect. If you paste an HTML fragment, the fragment is automatically closed to prevent it from affecting subsequent text and elements. For example, this means if your scripts rely on ordinal positions in the document's all collection, after a pasteHTML, the sourceIndex into the document.all collection may point to a different element.
Comparing Ranges
You can create more than one text range at a time, using them for independent, simultaneous access to different portions of the text in an element. You can also copy a text range by using the duplicate method. This is useful if you want temporary access to a portion of the original range but don't want to bother recreating or restoring the original range. You can determine the relationship of one text range to another by using methods such as isEqual and inRange.
Because the object model never holds on to a text range, you'll need to recreate any range whenever control leaves and then reenters your code. For example, any text range objects created by an event handler are discarded when the event handler returns.
You can determine whether one range in entirely contained within another text range by using the inRange method. You can determine whether two text ranges are identical by using the isEqual method. Text ranges are identical if they start and end at exactly the same positions. Note that identical text ranges are always considered to be within one another, meaning the inRange method returns true for these.
You can set the start or end point of a range to match the start or end point of another range by using the setEndPoint method. The method takes two parameters: a string describing which end points to transfer, and a range from which the source end point is taken. The following example sets the end of the range "r1" to the start of "r2".
r1.setEndPoint( "StartToEnd", r2 )
You can also use "StartToStart", "EndToStart", and "EndToEnd" to set the end points.
You can compare the start or end points of two ranges by using the compareEndPoints method. This method compares the end points and returns -1, 0, or 1, indicating whether the end point of the first range is less than, equal to, or greater than that of the second.
A bookmark is an easy way to save the current start and end positions of a text range and quickly restore these positions when you need them. You create a bookmark for a given range by using the getBookmark method, which returns an opaque string that uniquely identifies the bookmark. (Opaque means the string cannot be examined or modified.) You use the string with the moveToBookmark method to move the text range back to the same start and end positions as when the bookmark was created.
Commands
You can use commands to apply formatting and to carry out special actions on the text of a text range. You execute a command by using the execCommand method. You supply a command identifier and provide any additional command parameters. For example, you can change text to bold by using the Bold command as in the following JScript example.
var rng = document.body.createTextRange();
rng.collapse();
rng.expand("sentence");
rng.execCommand("Bold");
The above example makes bold all text up to the first period in the document.
Not all commands are available at all times. You can determine whether a command is available for a given text range by using the queryCommandEnabled and queryCommandSupported methods. To determine whether a given command has already been applied, use the queryCommandState method to retrieve the state of the command. The state is true if the command has been applied.
Finding Text in the Document
You can search for a given string of text in a document by using the findText method on a TextRange object. This method starts the search at the beginning of the range and, if it finds the string, positions the range so that it entirely encloses the string. The following example uses findText to search for each instance of the word "sample" and displays a message identifying how many instances it found.
var rng = document.body.createTextRange();
for (i=0; rng.findText("sample")!=false; i++)
alert("There are " + i + " instances of sample");
In the above example, the collapse method moves the start of the text range to the same position as the end point, ensuring that the same instance of "sample" is not counted twice.
You can carry out a global search and replace by using findText and the text property. The following example searches for each instance of "sample" and replaces it with the word "final".
var rng = document.body.createTextRange();
for (i=0; rng.findText("sample")!=false; i++)
You can select the text that you find, making it easier for the user to see, by using the select method. Similarly, you can scroll the text into the user's view by using the scrollIntoView method. Together, these methods give you a way to make the result of a search clearly visible to the user. The following JScript example searches for the word "sample", selects the word, and then scrolls the word to the top of the window.
var rng = document.body.createTextRange();
if (rng.findText("sample")==true)
Positioning
Microsoft Internet Explorer 4.0 supports the ability to position HTML elements in x- and y-coordinates, as well as overlap elements in planes along the z-axis, which extends toward and away from the viewer in a Web document. This capability allows authors to place elements-images, controls, or text-exactly where they want on the page. By using scripts to manipulate the position coordinates and other dynamic styles, authors can move elements around a page, creating animated effects. The combination of dynamic styles, positioning, transparent ActiveX Controls, and transparent images presents authors with a rich set of animation options.
What Is Positioning?
CSS Positioning defines the placement of elements on a page, and is an extension of cascading style sheets as specified in the W3C Working Draft on Positioning HTML with Cascading Style Sheets. By default, elements "flow" one after another in the same order as they appear in the HTML source, with each element having a size and position that depends on the type of element, the contents of the element, and the display context for the element as it will render on the page. This default "flow" model for HTML layout doesn't provide the author a high level of control over the placement of elements on the page. By applying a small set of CSS attributes to the elements that are defined for the page, you can control the precise position of elements by giving exact coordinates, or specifying placement relative to the position of other objects on the page.
Just like any other HTML or CSS attribute, the CSS attributes used to control an element's position are available for scripting. The position of these elements on the page can thus be dynamically changed with script. This is very powerful! The position of these elements can be recalculated and redrawn after the document is loaded without needing to reload the page from the server.
Controlling the position of an element uses several other layout control techniques. These include controlling the display of the object-that is, whether or not the element is displayed on the page, and how much of the element can be viewed by the user.
There are two ways to position an element in x- and y-coordinates. The type of positioning to use depends on the layout of the content and the purpose of the document. Absolute positioning means that the element is precisely placed relative to the parent coordinate system, regardless of any other content. Relative positioning places the item with respect to other elements on the page. Relative positioning depends on the default flow of the document, and reflows content should the user resize the browser.
Absolute Positioning
An absolutely positioned element is always relative to either the next positioned parent or, if there isn't one, the BODY by default. Values for left and top are relative to the upper-left corner of the next positioned element in the hierarchy. For example, to place an image at the top left corner of the document, you set the attributes to 0 as follows:
<IMG SRC="sample.gif" STYLE=" left:0; top:0">
This positions the image within the border of the BODY element. Remember, there is a default border on the BODY, so if no border is desired, set the border of the BODY to 0 to position the image at the 0,0 coordinates of the client area.
To see how a positioned parent affects the absolute position, consider the following example.
<DIV STYLE=" left:50;top:30;height:100;width:100">
Some text inside the DIV that will be hidden by the image because the image will be
positioned over this flowing text.
<IMG SRC="sample.gif" STYLE=" left:0; top:0">
</DIV>
This example places the IMG element at the upper-left corner of the DIV element, which is itself positioned on the page.
Setting an absolute position pulls the element out of the "flow" of the document and positions it regardless of the layout of surrounding elements. If other elements already occupy the given position, they do not affect the positioned element, nor does the positioned element affect them. Instead, all elements are drawn at the same place, causing the objects to overlap. You can control this overlap by using the z-index attribute to specify the order in which elements are stacked at the same location.
The contents of a positioned element flow within the given dimensions as default HTML would flow. For instance, text would wrap normally based on the width of the element, and various inline elements contained within the positioned elements will be placed next to each other in source order according to the constraints of size and shape of the "container" (that is, the positioned element).
Relative Positioning
Setting the CSS position attribute to "relative" places the element in the natural HTML flow of the document but offsets the position of the element based on the preceding content. For example, placing a piece of text within a paragraph with "relative" positioning renders the text relative to the text in the paragraph that precedes it.
<P>The superscript in this name
<SPAN STYLE="position: top:-3px">xyz</SPAN>
is "xyz".
</P>
Should the user resize the window, the "xyz" still appears three pixels above the natural baseline of the text. You can set the left attribute in a similar way to change the horizontal spacing between "name" and "xyz". If the contents of the SPAN were absolutely positioned, the "xyz" would be placed relative to the BODY (or the next positioned element in the hierarchy), and the "xyz" would be barely visible at the upper corner of the client area-not the effect the author probably intended!
Text and elements that follow a relatively positioned element occupy their own space and do not overlap the natural space for the positioned element. Contrast this with an absolutely positioned element where subsequent text and elements occupy what would have been the natural space for the positioned element before the positioned element was pulled out of the flow.
It is quite possible that relatively positioned elements will overlap with other objects and elements on the page. As with absolute positioning, you can use the z-index attribute to set the z-index of the positioned element relative to other elements that might occupy the same area. By default, a positioned element always has a higher z-coordinate than its parent element so that it will always be on top of its parent element.
Positioning Considerations
The type of positioning to use depends on the layout of the content and the purpose of the document. Relative positioning depends on the default flow of the document and will reflow content should the user resize the browser. However, absolute positioning gives you the control to precisely place images and text no matter what the user does to the display.
Here is an example of nesting an absolutely positioned element within a relatively positioned element. The desired effect is to center text in a rectangle. In the past, you might build tables and use attributes to center the content inside a table cell. However, this layout restricts you to a static table. Using positioning, this content can be worked into a larger layout, and then you can add scripting that might, for instance, have each of these elements fall into place from somewhere outside the document as the user loads the page!
<HTML>
<HEAD><TITLE>Center the DIV</TITLE>
<SCRIPT LANGUAGE="JScript">
function doPosition()
</SCRIPT>
</HEAD>
<BODY onload="doPosition()">
<P>Some text in the beginning.</P>
<DIV ID=one STYLE=" top:10;height:200;width:200;
background-color:green">
Some text in the outer DIV
<DIV ID=two STYLE=" left:50;width:100;color:red;
border:red 2px solid">
Text in the inner DIV - color should be red
</DIV>
</DIV>
</BODY>
</HTML>
Example # 5 -
In the example above, the outer DIV "flows" with the contents of the document that precedes it, meaning it is positioned 10 pixels immediately after the first paragraph. The inner DIV has an initial absolute position, but this position is modified by the script function "doPosition" when the document is loaded. The offsetWidth and offsetHeight properties are used to calculate the new absolute position for an element. In the example above, you can also use the posLeft or pixelLeft property to center the images. These properties give alternate access to the left property, letting you set the position using a floating point number or an integer. There are similar pos* and pixel* properties that provide alternate access to the top, width, and height properties.
Combining Dynamic Positioning Techniques
The previous example can be expanded to manipulate multiple items on the page. Or, to animate this script, you might rework the scripting function on the "onload" of the document to have the inner piece of text "fly in" from offscreen. This function could be based on a timer that would move the inner DIV from an initial top and left coordinate somewhere off the visible portion of the page, and, over a given amount of time, move it to a position that would be in the center of the outer DIV.
The following example makes the DIV element visible and animates the content to glide across the screen. By setting an interval using the setInterval method on the window object, you can move one or more elements each time the interval elapses.
<HTML>
<HEAD><TITLE>Glide the DIV</TITLE>
<SCRIPT LANGUAGE="JScript">
var action;
function StartGlide()
function Glide()
}
</SCRIPT>
</HEAD>
<BODY onload="StartGlide()">
<P>With dynamic positioning, you can move elements and their content
anywhere in the document even after the document has loaded!
<DIV ID="Banner" STYLE="visibility:hidden;
top:0; left:0">
Welcome to Dynamic HTML!
</DIV>
</BODY>
</HTML>
Example # 6 -
Note that you cannot dynamically change an element from nonpositioned to positioned. The position attribute should be set in the HTML source, as setting the position attribute in script will not work with Internet Explorer 4.0.
Controlling Content Visibility
In addition to controlling where on the page the element is positioned, the content of positioned elements can be restricted from the user's view in several ways. The display and visibility attributes control whether the element appears on the screen at all, and the clip and overflow attributes control how much of the content the user can see. As mentioned previously, authors can also control the visibility of overlapping elements by manipulating the z-index ordering.
Clipping Regions and Overflow
You can set a clipping region for a positioned element by using the clip attribute. The clipping region defines a rectangle within which the element is visible. Any portion of the element that extends outside the clipping region is "clipped," that is, not displayed. The clipping region does not alter the HTML, but simply changes how the element is displayed.
For example, the following document uses clip to define a clipping region for the absolutely positioned DIV. The region, a 30-by-30 pixel square, displays only a portion of the text; the rest is clipped from view.
<HTML><HEAD><TITLE>Clip the DIV</TITLE></HEAD>
<BODY>
<DIV STYLE=" top:50;left:50;height:100;width:100;
clip:rect(0 30 30 0);background-color:green">
some content some content some content some content some content
some content some content some content some content some content
some content some content some content some content some content
some content some content
</DIV>
</BODY>
</HTML>
Example # 7 -
Be careful when you define a clipping region-the parameter order (top, right, bottom, left) is important. For example, setting clip:rect to (0 0 30 30) causes the region not to display because the top and right have been defined as zero. The correct definition for a 30-by-30 clipping region based off the top left corner of the positioned object is to set clip:rect to (0 30 30 0).
You can change the clipping region dynamically by using the clip property, as in the following example.
document.all.MyDiv.style.clip = "rect(0 50 75 0)";
Overflow occurs when there is more content in a positioned element than can fit within the area defined for it. By default, any extra content is displayed but flows beyond the end of the area and therefore may overlap other elements in the document. You can prevent this overflow by using the "overflow" attribute to either hide the overflow or enable scroll bars to let the user view it by scrolling.
For example, the following document uses "overflow" to apply scroll bars. Only the portion of the text that fits within the 100-by-100 area is initially displayed, but the user can scroll the rest into view by using the scroll bars.
<HTML><HEAD><TITLE>Scroll the Overflow</TITLE></HEAD>
<BODY>
<DIV STYLE=" top:50;left:50;height:100;width:100;overflow:scroll">
some content some content some content some content some content
some content some content some content some content some content
some content some content some content some content some content
some content some content
</DIV>
</BODY>
</HTML>
Example # 8 -
You can hide any overflow by setting "overflow" to "hidden". Similarly, you can let the overflow flow beyond the end of the area by setting it to "visible". You can change the overflow dynamically by using the overflow property, as in this example.
if (document.all.MyDiv.style.overflow != "scroll")
document.all.MyDiv.style.overflow = "scroll";
Z-Index Ordering
The z-index specifies in what order elements should be drawn when two or more elements occupy the same area. Setting the z-index is useful whenever you have absolute or relative positioned elements that overlap other elements in the document. You set the z-index by using the z-index attribute. Setting this to a positive value causes the element to be stacked on top of other elements; negative values cause it to be stacked below. The following document uses z-index to stack text on top of the image.
<HTML><HEAD><TITLE>Stack the Image</TITLE></HEAD>
<BODY>
<P STYLE=" top:0; left:0">Text Over Image</P>
<IMG SRC="sample.jpg" STYLE=" top:0; left:0; z-index:-1">
</BODY>
</HTML>
Example # 9 -
The element with the greatest z-index is always placed at the very top of the stack, and the element with the least z-index at the very bottom. If two elements have the same z-index, their source order determines the stacking-the last element is stacked highest. You can change the z-index dynamically by setting the zIndex property:
document.all.MyImg.style.zIndex = 2;
In general, all elements are "windowless" and will participate in z-order overlapping. However, some objects are "windowed". ActiveX Controls that have not been specifically written to be windowless will not overlap with other objects. IFRAME elements represent a window object, and window objects do not participate in z-order. Another exception in Internet Explorer 4.0 is the SELECT element.
Element Visibility
The visibility of a positioned element determines whether the user can see the element. Visibility is useful for temporarily hiding an element, such as when time is needed to calculate its position or when carrying out simple transition effects. You can set the visibility by using the visibility attribute. The following example uses the attribute to make the DIV element invisible.
<p> A paragraph above the DIV element</p>
<DIV ID=MyDiv STYLE=" top:50;left:50;height:100;width:100;
visibility:hidden">
<p> A paragraph below the DIV element</p>
You can set the visibility of an element from script by using the visibility property. For example, assume that the DIV in the previous example is loaded. Initially, it is invisible, but you can change this to visible by using the following:
document.all.MyDiv.style.visibility = "visible";
An invisible element continues to affect the document layout; that is, the space that the element would occupy remains in the document even though it is empty. This is unlike the display attribute, which does not reserve space.
Filters and Transitions
With the introduction of Microsoft Internet Explorer 4.0, Web page authors now can apply multimedia-style effects to their content through the use of visual filters and transitions. These effects are implemented in Web pages using a Cascading Style Sheets (CSS) attribute. Visual filters and transitions can be applied to standard HTML controls, such as text containers, images, and any other windowless object. Transitions are time-varying filters that can create a transition from one visual state to another. By combining filters and transitions with basic scripting, authors have a powerful tool for creating visually engaging and interactive documents.
Creating Multimedia Effects
Visual filters are extensions to Internet Explorer 4.0 behavior that create onscreen effects in a document's contents. In some cases, filter effects are little more than prepackaged behavior that could have been done otherwise as script. In other cases, they go far beyond script and modify the rendered appearance of a control. Using visual filters greatly simplifies the task of incorporating sophisticated effects in Web documents.
Filters are applied to HTML controls through the filter style sheet property. The filter property is a string of filter descriptions that uses a function-like notation but does not require any knowledge of scripting. The syntax for a filter property in a style attribute is:
filter:filtername(parameters)
Here's an example of how filters are written as style attributes.
<img id=sample src="sample.jpg" style="filter:blur(strength=50) flipv()">
The sample HTML above attaches two filters to the IMG control. The first causes the image to blur over a specified number of pixels. The second filter flips the image vertically.
Each filter can have a set of optional parameters to define the precise nature of the effect, such as color or duration of behavior. Some filters, such as FlipV and FlipH for vertical and horizontal mirror images, have no parameters (although all filters and transitions have an enabled property, and all transitions have a Duration property). Multiple filters can be applied so that in the above example the "flipv" and "blur" filters are applied in combination to the IMG.
Filters often create effects that can also be generated with script. This raises the question, "Why use filters if script can do the job?" There are several reasons for using filters. Probably the most important is because they don't require script. For better or for worse, many HTML authors shy away (or are kept away) from scripting. Filters are a convenient package for the same functionality that scripting can provide. Another benefit of filters over script is that because they use the declarative and inherited syntax of CSS, they are easier to author and can be applied to entire classes of elements.
Another reason for using filters is because they provide a good downlevel story. Browsers that don't support the filter property or even style sheets simply ignore them. Even browsers that do support the filter property can do so in totally different ways without affecting the author. For instance, while filters in Internet Explorer 4.0 are implemented as special COM objects and can be easily extended, it is likely that the Windows® 3.1 implementation will be built in and represent a subset of the Internet Explorer 4.0 functionality.
Although all the filters that ship with Internet Explorer 4.0 are "visual," it is not a requirement. An example of a nonvisual filter would be a filter that changed various style sheet attributes (such as color, font size, bold, and even position) on the filtered element. These filters can be applied to any element (not just controls).
What Are HTML Controls?
Visual filters can be applied only to HTML elements that are controls. A control element defines a rectangular space within a browser window when the browser renders the Web document. Controls cannot be windowed, such as an IFRAME. Valid HTML controls are:
BODY, BUTTON, DIV (with a defined height, width, or absolute positioning), IMG, INPUT, MARQUEE, SPAN (with a defined height, width, or absolute positioning), TABLE, TD, TEXTAREA, TFOOT, TH, THEAD, TR.
Windowless controls, such as structured graphics and ActiveX Controls, can also apply filter attributes. Filters follow the standard CSS attribute inheritance scheme (if it exists for the object) except for the exceptions noted below.
Filters are ignored for any positioned elements nested inside nonpositioned elements, such as a positioned SPAN inside a nonpositioned DIV. The simple solution is to always position or define a width for your outermost element.
Elements and windowed objects that cannot have filters applied to them include Java applets, IFRAME, the SELECT and OPTION form elements, P paragraph elements, Hn headings, and EM and STRONG logical text style elements.
Defining Visual Filters
Visual filters modify the appearance of a control. In fact, they can totally take over the visual output of a control when applying their effect. A good example of a visual filter is the alpha filter. It blends its target into the background. The author controls the amount of blend (or opacity). Opacity is expressed as a percentage. For example, the following causes the image to be 20 percent opaque:
<img id=sample src=sample.jpg style="filter:alpha(opacity=20)">
Internet Explorer 4.0 supports a range of visual filters, shown in the following table, from the aforementioned alpha blend to a light filter that simulates colored lights shining on the control.
Filter effect |
Description |
Alpha |
Sets a transparency level. |
Blur |
Creates the impression of moving at high speed. |
Chroma |
Makes a specific color transparent. |
Drop Shadow |
Creates an offset solid silhouette. |
FlipH |
Creates a horizontal mirror image. |
FlipV |
Creates a vertical mirror image. |
Glow |
Adds radiance around the outside edges of the object. |
Grayscale |
Drops color information from the image. |
Invert |
Reverses the hue, saturation, and brightness values. |
Light |
Projects light sources onto an object. |
Mask |
Creates a transparent mask from an object. |
Shadow |
Creates a solid silhouette of the object. |
Wave |
Creates a sine wave distortion along the x-axis and y-axis. |
XRay |
Shows just the edges of the object. |
Scripting Filters
A filters collection is available on every element to provide script with access to their individual filters. The collection can be accessed like any other object model collection. For example, the following line of script addresses the first filter in the collection of filters on the element with id=theDiv.
theDiv.filters.item(0).enabled = true;
Filters are considered sub-objects of the control to which they are attached. Like other objects, they expose properties and methods for changing their internal state. Like other object model collections, the filters collection supports several kinds of access.
<img id=sample src="sample.jpg" style="filter: alpha(opacity=50) fliph(enabled=0)
blur(amount=10); position: relative">
<script language="JavaScript">
function foo()
</script>
The numeric access is particularly useful when more than one filter of the same type is applied or when the type of filter isn't known in advance (if it is set through script or data binding, for instance). This is particularly important for filters and transitions that have common properties and methods such as Amount, Color, and Play.
In the following example, the opacity of a control is dynamically changed by changing the opacity property on the alpha filter.
<img id=sample src=sample.jpg style="filter: alpha(opacity=50)">
<script language="javascript">
function foo()
This same syntax can be used to call the methods needed to make the transition revealTrans work in the following example.
<div id=mydiv style="height:50;width:50;filter:wave(strength=100)
revealTrans(transition=3 duration=4)">
This is a div
</div>
<script language="JavaScript">
mydiv.filters.revealTrans.apply()
mydiv.innerText = "This is different text"
mydiv.filters.revealTrans.play()
</script>
Alternately, revealTrans can be accessed by index.
<script language="JavaScript">
mydiv.filters[1].apply()
mydiv.innerText = "This is different text"
mydiv.filters[1].play()
</script>
The Filter String
The style object also has a filter property. This is a read/write string that can be used to manipulate the CSS filters of an element directly. For instance, using the DIV defined above, the following code:
<div id=mydiv style="height:50;width:50;filter:wave(strength=100)
revealTrans(transition=3 duration=4)">
This is a div
</div>
<script>
... alert(mydiv.style.filter)...
</script>
Would produce an alert with the following string:
wave(strength=100) revealTrans(transition=3 duration=4)
Writing to this property is especially useful to change an element's filters dynamically. Note that writing to this property overwrites the existing value and the browser renders the new string immediately. The following example adds a FlipH filter to a collection on the fly.
<div id=mydiv style="height:50;width:50;filter:wave(strength=100)
revealTrans(transition=3 duration=4)">
This is a div
</div>
<script>
... mydiv.style.filter = mydiv.style.filter + "fliph()"...
</script>
After the change, the new filter string would now look like this:
wave(strength=100) revealTrans(transition=3 duration=4) fliph()
Any additional changes to that collection's filter string will modify the new string. For complex filter manipulation, authors need to keep track of the current states of their element filter collections.
Note It is strongly recommended that CSS filters be accessed through the object model whenever possible, and the filter string be accessed only under special circumstances where object model functionality is not adequate. Even in the case of dynamically adding filters, it is recommended in most cases to actually add the filter in the initial filter attributes of the element's style sheet with enabled=0. When the script wants the filter to be displayed, it can then simply set that filter to enabled=1 and the filter will be displayed.
Migrating from OBJECT-based Filters
As Internet Explorer 4.0 was developed, filters were initially supported as OBJECT elements. With the release of the final version of Internet Explorer 4.0, filters made the logical switch to the CSS model for implementation. While this switch won't have any effect on new Web pages, existing documents that employed filter effects as objects are now broken. Authors who are accustomed to using objects and enjoyed the ability to apply a single object to many different controls at once must now specify the filters on each control that will use them. However, since you can change the style.filter string in script, the old-style syntax can be approximated as follows:
<object id=aFilter clsid=...>
<param name=param-name value=param-value> ...
</object>
site.filter = aFilter
This becomes:
site.style.filter = "someFilter(param-name=param-value, ...)"
However, this solution is hardly the best way to use filters. The new CSS syntax allows multiple filters to be attached and active at once. The Enabled property can be used to turn a given filter on and off.
Filter Design Considerations
Some filters require transparency to function properly. These include Shadow, DropShadow, Glow, and Mask. Text automatically has "transparency," or space around the characters that shows through to the object (or page) behind it. GIF images must be in gif89a format with a transparent color to display these filters properly.
Margins can affect how some filters are applied and rendered. "Clipping" can occur when a margin or DIV boundary is set too close to an object that has a filter applied to it. For instance, applying a glow to text without a margin may have some of the glow effect clipped by the DIV boundary if the text is directly next to it.
Performance is an important factor to consider when designing Web pages with filters. Internet Explorer 4.0 requires processing time to calculate the visual display of filter effects, and some require more time than others to apply. It is useless to try to apply and change a filter on an element before the browser can even render it (such as manipulating a light effect quickly in a looping script function).
While selecting text in the browser window, any applied filter effects are ignored. Once the mouse button is released, the browser reapplies the filter effects to the text. This operation is subject to any performance limitations that were previously experienced.
It is possible to apply one or more filter effects to a group of elements by wrapping them in a DIV. Take care that the DIV itself is positioned if the enclosed elements are positioned. As noted previously, filters require that all containers be either positioned or have defined widths, and parent elements be positioned to display filter effects properly on child elements.
Filters have different methods for creating their effects on elements. For example, the alpha filter affects each pixel as a function of itself (creating either a uniform or gradient effect), while with the glow filter, each pixel inherits from the pixels directly around it, creating a diminishing effect. Your choice of content might be affected by the application method a filter requires to achieve its effect.
Transitions
Transitions are time-varying visual filters. Their role is to visually transition a control from one state to the next. A common example is changing the SRC of an image to change one image to another onscreen. A transition would provide some kind of animated effect to bring in the new image. Transitions can also be applied to make a control gradually fade in or fade out by changing the visibility property.
Transition filters have methods and events for manipulation. When the filter wants to fire an event, the onfilterchange event is fired. This event can be used to script the srcFilter property on the event object, and then supplies all the necessary information about the event. In this way a script can know when a transition has completed. The methods for the filters allow a transition to be applied and played.
The Apply method freezes the visual appearance of the control by first applying the transition, allowing changes to be made without an immediate repaint such as specifying a new image. The Play method then invokes the transition. At any time, the script can "cut to the chase" and finish the transition by calling Stop. The following example shows how to perform an automatic slide show between images.
<HTML><HEAD><TITLE>Transition Blend Demo</TITLE>
<SCRIPT language="JavaScript">
var fRunning = 0
function startTrans()
}
</SCRIPT>
<SCRIPT for="SampleID" event="onfilterchange">
fRunning = 0
</SCRIPT>
</HEAD>
<BODY>
<IMG id="SampleID" src="beach.jpg" style="filter:blendTrans(duration=3)"
onclick="startTrans()">
<BR> Click image for Transition Filter: Blend
</BODY>
</HTML>
Example # 10 -
Two transition filters ship with Internet Explorer 4.0, blend and reveal. The blend transition allows a simple fade-in or fade-out with a specified duration, while the reveal transition specifies multiple effects such as boxin, boxout, horizontal blinds, and so on.
The following HTML is an example of a simple transition between two images. Clicking the button runs the doTrans script, which first calls Apply on the revealTrans filter to stop painting of the image. It then sets an alternative image and calls Play on the filter to proceed with the transition. In this case the transition type is set to 8, which corresponds to the vertical blinds transition effect. This is applied using an inline style on the IMG tag.
<HTML>
<HEAD><TITLE>Transition Sample</TITLE>
<SCRIPT LANGUAGE=JavaScript>
Function doTrans()
</SCRIPT>
</HEAD>
<BODY style="background-color:darkblue">
<IMG ID=theImg width=200 height=200 src="clouds.bmp"
style="filter:revealTrans(Duration=3.3, Transition=8);">
<BR>
<INPUT type=button value="Start Transition" onClick="doTrans()">
<IMG src="clouds.bmp" style=" width:1; height:1;visibility:hidden">
<IMG src="circles.bmp" style=" width:1; height:1; visibility:hidden">
</BODY>
</HTML>
Example # 11 -
This example also demonstrates the differences between asynchronous and synchronous changes. Changing the innerText of an element is synchronous-the action is completed by the time the statement has executed. Changing the src is effectively asynchronous. Although the actual src property changes immediately, the visual state of the IMG element isn't fully updated until the actual download of the new image is complete. A careful script would wait for the onload event on the image. "Pre-loading" graphics with separate IMG tags is a good way to avoid the synchronicity issue but it will only work if the transition is applied after all image downloads are complete.
Interpage Transitions
Interpage transitions make it possible to provide visual effects to the entire window as a Web page is loaded or exited. Just as programs such as PowerPoint® allow for transitions between slides, you can provide wipes, fades, and even create custom transition types.
Transitions are implemented with
Transition Syntax
The syntax for transitions consists of three parts: specifying when the event should be played, the duration of the transition, and what kind of transition effect to use. The following two examples show how to set transitions upon entry and exit of a page.
<META http-equiv="Page-Enter"CONTENT="RevealTrans(Duration=4,Transition=1)>
<META http-equiv="Page-Exit"CONTENT="RevealTrans(Duration=2.5,Transition=6)>
The first META tag causes transition 1 to
play when the user enters the page, lasting 4 seconds; the second
There are four events that can initiate interpage transitions: Page-Enter , Page-Exit, Site-Enter, and Site-Exit. Duration has a maximum value of 30 seconds.
Transitions Reference
The available reveal transitions that are supported in Internet Explorer 4.0 are described below.
Transition name |
Value |
Box in | |
Box out | |
Circle in | |
Circle out | |
Wipe up | |
Wipe down | |
Wipe right | |
Wipe left | |
Vertical blinds | |
Horizontal blinds | |
Checkerboard across | |
Checkerboard down | |
Random dissolve | |
| |
Split vertical out | |
| |
Split horizontal out | |
Strips left down | |
Strips left up | |
Strips right down | |
Strips right up | |
Random bars horizontal | |
Random bars vertical | |
Random |
Transition Design Considerations
The primary concern of designers when implementing transitions is that, since they run asynchronously, it is necessary to track each transition state through events (onfilterchange) to determine when a particular transition is finished. Remember that image downloading is asynchronous and that the visual state of IMG elements isn't fully updated until after images are completely downloaded.
Font Embedding
Web page designers are at a disadvantage compared to print desktop publishers when creating documents; desktop publishers control every aspect of the layout and choose which fonts their content will be printed in. On the other hand, Web authors are at the mercy of the browser and the user's font support when their content is displayed.
Font embedding has been a feature of Microsoft applications such as Microsoft Word and PowerPoint for several years. It allows fonts used in the creation of a document to travel with that document, assuring that a user sees the pages exactly as the author intended them to be seen. Now, Microsoft Internet Explorer 4.0 brings embedded font support to the Web. This technology gives site designers the confidence that Internet Explorer 4.0 users will see their pages exactly as intended.
Embedded Font Technology
In the early years of the World Wide Web, browsers had full control over which font was used to display pages. Later, the FONT element and Cascading Style Sheets (CSS) font-family property were introduced to provide the Web author more control and access to fonts installed on the user's system. However, if the font was not previously installed on the user's computer, the author and user had no recourse but to display the document in a default or secondary font face. Today, Internet Explorer 4.0 supports font embedding, allowing authors to temporarily install fonts on user systems so that Web page content can be rendered exactly as intended.
At this time there is no defined industry standard for font embedding. The Microsoft TrueType font embedding technology is one proposed implementation. The World Wide Web Consortium (W3C) has a working draft available that provides the latest proposed specifications.
Microsoft font embedding uses CSS notation to indicate font styles in Web documents. Designers can limit the frequency that embedded fonts must be transferred to the users' computers if they anticipate fonts that might already be installed. The following example uses an embedded font as a secondary font face, if by chance the preferred font is not already installed on the client computer.
<STYLE>
<SPAN style="COLOR: red">@font-face myfont
</SPAN>
P
</STYLE>
Different Levels of Font Embedding
TrueType fonts have embedding permissions encoded within them that determine how they can be used by tools that convert them into the embedded font format. There are four levels of embedding:
No-embedding permissions are used by a small proportion of available fonts. The creators of these fonts have decided not to allow embedding. Some foundries set their fonts to no-embedding but offer upgrades to embeddable versions. If you come across a no-embedding font that you would really like to use, contact the supplier and ask about a possible upgrade.
Print and preview fonts can be embedded, but only within pages that remain static on the client side. If a page allows client-side interaction that results in content displayed using the font changing, "editable" or "installable" fonts must be used. An example of such a page might be one that contains an inline JavaT-based word processor, or an e-mail editor.
Editable fonts can be embedded using a tool such as WEFT (Web Embedding Fonts Tool) without the restrictions imposed on "print and preview" fonts.
Installable fonts are treated as editable fonts by Internet Explorer 4.0. Installable fonts will not be installed in your visitors fonts folder. The main reason for this is that during the course of users' Web travels, they could easily find their fonts folder stuffed with hundreds of full and subsetted fonts that they do not want or need.
Limitations in Internet Explorer 4.0
At present Microsoft Internet Explorer 4.0 downloads, decompresses, and privately installs font objects even if the real font is installed on a user's system. Future versions will check if the real version of the font is available before downloading the linked font object. Currently this behavior has to be simulated using VBscript or JScript.
The W3C font embedding draft also describes the way in which browsers should be able to combine font objects containing different subsets of the same font. This way you could link to a font object that contains the uppercase letters from a particular font and another font object containing lowercase letters. At present Internet Explorer 4 uses only the first font object specified.
Internet Explorer 4.0 Security Alert
Depending on how Internet Explorer 4.0 security settings are set, you might get a warning every time a page accesses an embedded font. Although your security level settings can easily be modified, you should first access the Internet Explorer online help and read the sections discussing security before making the following changes:
On the View menu, click Options and then click the Security tab.
Select Custom and click Settings.
Scroll down to the Downloads section.
Change the Font Download setting from Prompt to Enable.
Using Microsoft WEFT
The Microsoft Web Embedding Fonts Tool is being released to coincide with the release of Internet Explorer 4.0. WEFT is a free utility that lets site designers create font objects that are linked to their Web pages. Download the current version of WEFT for Windows 95 and Windows NT from the Microsoft Typography Web site.
The font objects created by WEFT differ from traditional font files in a number of ways. The font objects are compressed and are usually subsetted so that they contain only the characters used by a particular site or page. They are also privately installed by Internet Explorer 4.0 so that they can't be accessed by other applications, and they can't be linked to sites that don't have permission to use them. In the future, WEFT features will be built into popular Web authoring tools.
WEFT Style Code
WEFT adds a STYLE section to the HEAD part of each HTML page that uses one or more font objects.
<STYLE TYPE="text/css">
@font-face
</STYLE>
This code tells Internet Explorer 4.0 to use the Garamond1.eot font object whenever the Garamond Italic font is specified within the page. The browser will use the font object regardless of whether the font is specified using the FONT FACE tag, a linked or inline Cascading Style Sheet, or some other method.
Cascading Style Sheet Files
WEFT uses Internet Explorer 4.0 to determine the fonts and characters used on each page. If a page references a linked style sheet, this style sheet usually determines the fonts Internet Explorer 4.0 uses to display the page. Note that WEFT does not modify linked style sheets. Instead, the tool modifies the HTML pages by adding code that links the font objects to pages that require them.
In some cases it will be more efficient to reference the font objects within one or more linked style sheets. If you'd like to try this, skip the option asking if you want to publish the modified pages back to your Web site. Instead, cut and paste the relevant code from the modified pages (by default these will be stored in the My Documents folder) into your linked style sheet.
A word of caution is needed. As style sheets cascade, a font specified in a linked style sheet may be overridden by one specified inline. Also, because a style sheet can be linked to any number of pages, care should be taken when choosing an appropriate subsetting level.
|