Click to return to the DHTML, HTML     
Knowledge Base Articles     Overview    
Web Workshop  |  DHTML, HTML & CSS

Frequently Asked Questions


Printing this FAQ?

General Questions

Dynamic HTML

Technical Questions

HTML Coding

DHTML Editing Component

Frequently Asked Questions about HTML Coding

Steve Pruitt

Updated: October 7, 1998


Tables

How can I create a blank cell in a table that displays its borders?

Put a non-breaking space character in the cell using " ".

How can I space out a table cell with blank lines?

Users often ask how they can space out items vertically in a tabled list. Adding a <P> tag at the end of each cell doesn't work because Internet Explorer ignores tags that don't contain any content. Instead, use <P> and <BR> tags (or two <P> tags, depending on how much space you need) and add a non-breaking space in between:

<p>&nbsp;<br>

Frames

Why does my page display as blank with some browsers?

Pages that use frames must also include content for browsers that do not support frames. You include the alternate content in the <NOFRAMES> section of your frameset document. If you don't provide this content, your page will appear blank in Internet Explorer 2.0 or other browsers that don't support frames. See the next question for more information on coding for non-frame browsers.

How do I code frames to be compatible with non-frame browsers?

The document containing your frameset commands must also contain a <NOFRAMES> section that contains the HTML material you want the other browsers to display, for example:

<HTML>
<HEAD>
</HEAD>
<FRAMESET COLS="80,100%" FRAMEBORDER="no" FRAMESPACING=0>
<FRAME SRC=  NAME=  >
<FRAME SRC=  NAME=  >
<NOFRAMES>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#000000">
Content to be displayed by other browsers...
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>

Browsers that don't support frames will ignore the <FRAMESET>, <FRAME>, and <NOFRAMES> tags and will display the contents of the <BODY> section.

Note: The <FRAME> tags should not appear between <BODY> and </BODY> tags.

How do I create a link that changes the content of a different frame?

Include TARGET="framename" in the link, for example:

<A HREF="http://www.my.com/my.htm" TARGET="frame1">

Note that target names are case sensitive. You can also use any of the following predefined target names:

Target name Description
_blank Load this link into a new, unnamed window.
_self Load this link within the current frame.
_parent Load this link into your parent frame (same as self if current frame has no parent).
_top Load this link at the topmost level (same as self if current frame is at the top).

Why do my links open a new window instead of changing the frame contents?

Internet Explorer interprets target frame names strictly and is case sensitive. For example, if you define a frame called "FRAME1" and have an anchor that links to "frame1," the target name will not be recognized. Links to undefined targets open new windows.

How do I create a link that changes two or more frames?

One easy method is to link to a new frameset page using TARGET="_top". Any documents or images common to both framesets will be loaded quickly from the cache.

You can change two frames at once by using scripting within the anchor:

<A LANGUAGE="VBScript" HREF="http://target1.htm" TARGET="frame1"
onClick="parent.frame2.location.href='http://target2.htm'">

The HREF and TARGET on the first line specify the update for one frame, and the second line includes a script that changes the second frame. Substitute the appropriate frame names in each case. Note that you may need other changes in the script, depending on the structure of your page.

You can use scripting to change selected frames and (optionally) to perform other functions from a single click, as follows:

<A HREF="" name="ClickMe">Click me!</A>
<SCRIPT Language = "VBScript">
<!--
SUB ClickMe_OnClick()
   parent.FrameOne.location.href="my_gif.gif"
   parent.FrameTwo.location.href="my_htm.htm"
END SUB
-->
</SCRIPT>

How do I reference floating frames?

If you are using only floating frames, you can reference them exactly like standard frames:

<IFRAME SRC="page1.htm" NAME="Frame2"></IFRAME>
parent.frames(0).location.href="newpage.htm"
<A HREF="newpage.htm" TARGET="Frame2">

If you combine floating frames with regular frames, the floating frames have to be treated differently. Floating frames are added to the document object, not to the '"regular" frames collection. (This information wasn't included in the SDK documentation, but it will be added in a future version of the documentation.)

To access a floating frame on the current page, use the following:

document.FloatingFrameName.whatever

To access a floating frame in a different frame, use the following:

top.frames[n].document.FloatingFrameName.whatever

How do I refresh a frame or an entire window during testing?

To refresh a frame, right-click within the frame and select Refresh from the shortcut menu, or left-click within the frame and click the Refresh button on the Internet Explorer toolbar. Press F5 to refresh the entire frameset.

How do I print the contents of a frame?

To print the contents of a frame, right-click within the frame and select Print from the shortcut menu, or left-click within the frame and click the Print button on the toolbar. Internet Explorer 4.0 allows you to choose printing the entire screen, the selected frame, or all frames individually. You cannot print the complete multi-frame window from Internet Explorer 3.0.

How can I use an image as a frame border?

You can use an image as a frame border by adding extra "border" cells to your table. Here's an example of a table that has a five-pixel-wide "border" tiled with the image "Test.gif":

<HTML>
<BODY>

<TABLE BORDER=0 CELLSPACING=0>
<!-- First row: three-cells wide and provides a "top border" -->
<TR>
   <TD HEIGHT=5 COLSPAN=3 BACKGROUND="test.gif"></TD>
</TR>
<TR>
   <!-- The following is the "left border" -->
   <TD WIDTH=5 BACKGROUND="test.gif"></TD>
   <TD>
      <!-- Your table contents go here -->
      <FONT SIZE=7>Hi there!</FONT>
   </TD>
   <!-- The following is the "right border" -->
   <TD WIDTH=5 BACKGROUND="test.gif"></TD>
</TR>
<!-- Last row: three-cells wide and provides a "bottom border"
-->
<TR>
   <TD HEIGHT=5 COLSPAN=3 BACKGROUND="test.gif"></TD>
</TR>
</TABLE>

</BODY>
</HTML>

Style Sheets

How are measurements handled?

In general, you should specify font sizes and line-height using point size rather than pixels. A font that is 16-pixels tall may look fine on the screen, but it looks small on a 300-dpi printer. For indents and other measurements, you might consider using inches.

What's the difference between the <DIV> and <SPAN> tags?

Think of <DIV> as a container version of <BR>. The <BR> tag allows you to add a simple line break into your document. The <DIV> tag, being a container, also allows you to specify additional attributes, such as CLASS for assigning a CSS class to this section.

If all you want to do is provide simple highlighting of a word or short phrase in a longer sentence without line breaks, use <SPAN>. This is a "do nothing" container tag that implies no default formatting of its own. However, it is a container, so you can assign a CLASS (or STYLE) attribute to it to achieve your goal.

Thus, to highlight a word in a sentence use the following code:

This is your last <span style="background:yellow; color:red; 

font-weight:bold">Warning</span>, proceed at your own risk.

How do I use external style sheets?

To use external style sheets, place your style definitions in a separate file with a .css extension, and link to this file from your Web page as follows:

<LINK REL=STYLESHEET TYPE="text/css" SRC="http://www.my.com/mystyle.css">

The external file must not include the

<style> 
<!--

and

-->
</style>

tags that are used for style sheets within a document.

Note: <BODY> settings do not work in external style sheets in Internet Explorer 3.0.

How can I create shadowed text?

Although CSS does support shadowed text (via text placement on the page), you should be careful using this feature because non-CSS-aware browsers will not be able to display it correctly. Think about how your page will look in other browsers, and determine whether the benefit of getting shadowed text via CSS is worth the cost of damaging your information in non-CSS browsers.

There are some excellent examples of text shadowing and other capabilities available via CSS on http://www.microsoft.com/typography/css/downloads/entrance.htm Non-MSDN Online Link, but these examples are not compatible with non-CSS browsers.

How can I set a font for the entire document?

Place a BODY command within the document head as follows:

<HTML>
<HEAD>
<STYLE>
<!--
BODY  {font-family:COMIC SANS MS}
-->
</STYLE>
</HEAD>
<BODY>
<H1>This</H1> is a sample page
</BODY>
</HTML>
The BODY command cannot be used in a linked external style sheet in Internet Explorer 3.0. You should always list alternative fonts in case the primary choice is not available, as explained in the next question.

Which fonts can I use?

A font has to reside on the user's computer in order to be displayed. This means that you must use fonts that either you can count on to be on the user's system or users can legally download through your site. You can and should list multiple fonts in order of preference to handle the cases where a desired font isn't available, for example:

<font face="Verdana, Trebuchet MS, Arial, Helvetica, Helv, Geneva, Swiss, Sans-Serif, System">

To a certain point, there is no way to solve the problems with cross-platform fonts just using the FACE attribute. Not only are you perhaps going to run into systems that you weren't expecting, but you can also run into systems where the user didn't install (or removed) the "common" font you were wanting. Depending on your actual needs, requirements, and expectations, a good way of dealing with this would be as follows:

<font face="Verdana, Arial, Helvetica, Swiss" style="font-family:'Verdana, Arial, sans-serif,';">

While this is sort of robust in the usage of the font FACE attribute, it is also taking advantage of the CSS addition of a "generic" font name. When the browser encounters "Sans-Serif" as a font name, it will undertake the task of locating a font on the system that matches that type. While which sans-serif font is selected is no longer in the authors scope, it does allow the author to say "I at least want a sans-serif font."

Additional information, including embedding fonts for use by Internet Explorer 4.0, is available at: http://www.microsoft.com/truetype/web/default.htm.

Be careful: Most commercial fonts are not licensed for redistribution. Read the license carefully for any fonts you have purchased before making them available on your site. Several fonts are installed with the full version of Internet Explorer 3.0, but are not included with the minimal installation. You can offer users a link to the Microsoft Typography page ( http://www.microsoft.com/typography/ Non-MSDN Online Link) to install these fonts, or use the following links to download individual fonts:

Forms

How can I control the use of the ENTER key to submit a form?

If you have a single form on your page, pressing the ENTER key submits the form, even if you don't have an <INPUT TYPE=SUBMIT> button. This can bypass your validation script. The easiest way to prevent this action is to define a second form on the page. It may be empty, or it may contain only a hidden form.

For example, place this after the real form:

<form method=get>
<input type="hidden">
</form

How can I have multiple Submit buttons on my form?

Although HTML won't allow multiple Submit buttons, you can simulate this with graphics that serve as Submit buttons combined with some scripting, for example:

<script language="javascript">
<!--

function submit_Form()
   {
      var formVariable = document.forms[0].myLittleTextBox.value
      location.href='http://name.domain/path/ISAPIApp?myLittleTextBox=' + formVariable
   }

function reset_Form()
   {
      alert('form being reset')
      document.forms[0].myLittleTextBox.value=''
   }
function submit_Form_DownloadFile()
   {
   //code for downloading file
   }

function submit_Form_ReadInformation()
   {
   code for reading information
   }          
//-->
</script>

<FORM METHOD="POST" ACTION="javascript:submit_Form()" name="testForm">
<input type="textbox" name="myLittleTextBox">
<INPUT TYPE=IMAGE SRC="babble.gif" NAME="whatever">
</FORM>

<a href="javascript:submit_Form_DownloadFile()"><IMG SRC="babble.gif"></a>
<a href="javascript:sumit_Form_ReadInformation()"><IMG SRC="babble.gif"></a>
<a href="javascript:reset_Form"><IMG SRC="babble.gif"></a>

How can I put a Submit button in a different frame from the form?

You can't have the form's Submit button in another frame because the button has to exist within the same <FORM></FORM> containment as the elements it needs to submit. However, you can call the Submit method of the form from another frame. For example:

<input type=button name=remote value="submit">
<script language="vbscript">
<!--
Sub remote_OnClick
   parent.document.frames(1).document.forms(0).submit
end sub
-->
</script>

This code will put a Submit button in the first frame of the page. When the user clicks the button, it will call the Submit method of the first form in the second frame.

How can I send mail from my forms?

Internet Explorer handles a mailto command by opening a new mail message with the address filled in, but it does not consistently insert the Subject line or message text. Internet Explorer doesn't use an internal mail system; it can work with many different mail systems. The Subject line can be inserted only for mail clients that support this feature.

The most dependable way to use e-mail with a form is through a script or program on the server. Many Internet Service Providers (ISPs) provide such scripts to anyone with a Web site on their servers.

Warning: If you use a script that sends mail from your account to an address specified in the HTML page, someone could capture your HTML source and modify it to cause your server to send mail from your account to any address they want. For security, always use server programs or scripts that have the destination address hard-coded or that work only with HTML pages located on that server.

Special Effects with Marquees

How do I create a marquee that scrolls vertically?

You need to use the ActiveX™ marquee control that is included with Internet Explorer. The CODEBASE parameters are not required because this control will always be installed with the browser. The page that is to display the marquee will include code similar to the following (see the next question for specifics on how to control the scrolling direction and other variations):

<OBJECT
   ALIGN=CENTER 
   CLASSID="clsid:1a4da620-6217-11cf-be62-0080c72edd2d"
   WIDTH=100 HEIGHT=90 BORDER=0 HSPACE=0
   ID=marquee >
<PARAM NAME="ScrollStyleX" VALUE="Circular">
<PARAM NAME="ScrollStyleY" VALUE="Circular">
<PARAM NAME="szURL" VALUE="marqcont.htm">
<PARAM NAME="ScrollDelay" VALUE=60>
<PARAM NAME="LoopsX" VALUE=-1>
<PARAM NAME="LoopsY" VALUE=-1>
<PARAM NAME="ScrollPixelsX" VALUE=0>
<PARAM NAME="ScrollPixelsY" VALUE=-3>
<PARAM NAME="DrawImmediately" VALUE=0>
<PARAM NAME="Whitespace" VALUE=0>
<PARAM NAME="PageFlippingOn" VALUE=0>
<PARAM NAME="Zoom" VALUE=100>
<PARAM NAME="WidthOfPage" VALUE=100>
</OBJECT>

The page that is the marquee (referred to as Marqcont.htm in the code above) will have code similar to the following:

<TABLE BORDER=0>
 <TR>
   <TD WIDTH=100 HEIGHT=60 ALIGN=CENTER VALIGN=CENTER>
     <SPAN STYLE="font: 10pt/12pt Arial; color: purple; font-weight: bold">
     This site is enhanced for
     <BR>
     <IMG ALIGN=CENTER width=88 height=31 SRC="ie_stat.gif" border=0>
   </TD>
 </TR>
</TABLE>

What other scrolling effects can I create with marquees?

The ScrollPixelsX and ScrollPixelsY values control the direction of scrolling movement. X values control horizontal movement, and Y values control vertical movement. Positive values move to the right or bottom, negative values move to the left or top. Thus, X=0 and Y=-3 results in scrolling from bottom to top. If both the X and Y values are non-zero, the movements are combined, resulting in a slanted movement.

The Zoom parameter can be used to cause an explosive effect by contracting and expanding the contents.

Including the following lines in the OBJECT definition causes the contents of the marquee to switch between different contents when the user right-clicks the marquee.

<PARAM NAME="szURL" VALUE="alphabet.htm">
<PARAM NAME="PageFlippingOn" VALUE="1">
<PARAM NAME="OtherURL0" VALUE="alphabet2.htm">
<PARAM NAME="OtherURL1" VALUE="alphabet3.htm">

How can I control the background color of a marquee?

You cannot use BackColor with the Marquee control. Instead, set the BGCOLOR in the body of the HTML file being displayed by the control.

Why is my marquee being formatted incorrectly?

You cannot use any other tags, such as <FONT> or anchor (<A>), inside <MARQUEE> tags. They can be used outside, applying to the entire marquee, as follows:

<A HREF="nextpage.htm">< <FONT SIZE=+2><MARQUEE>Message Here</MARQUEE></FONT></A>

Authoring for Multiple Browsers

How can I detect which browser is being used?

Whenever possible you should be testing for the capabilities of the browser (for example, VBScript support), rather than identifying the browser. This will automatically handle upgraded versions of browsers. If that's not practical, you must use scripting code such as the following:

<SCRIPT LANGUAGE="JavaScript">
<!--
var ver = navigator.appVersion;
if (ver.indexOf("MSIE") != -1)
{
 window.location.href="ie.htm"
}
else{
   window.open("netscape.html", target="_self")
}
// --></SCRIPT>

A wide variety of scripts for detecting particular browsers, versions, and capabilities can be found by searching the archives of the IE-HTML mailing list Non-MSDN Online Link.

How can I embed a sound for both Internet Explorer and Netscape Navigator?

You can now use the <EMBED> tag for both browsers, as follows:

<EMBED SRC="sound.au" height=2 width=2 autostart=true hidden=true>

If you're going to use the sound as part of a complex page, place the tag towards the bottom of your code (but still within </BODY>). Wave files can take a little time to load and tend to hold up the display of your page while they do so. (This may cause users to click the Stop button in frustration before they see what you have to offer.)

Some site developers prefer to use browser-detection scripts that create different tags using features unique to each browser, for example:

<SCRIPT LANGUAGE="JavaScript">
<!--
var ver = navigator.appVersion;
if (ver.indexOf("MSIE") != -1)
{
 document.write('<BGSOUND SRC="tick.wav" LOOP=infinite>')
}else
 document.write('<embed src="tick.wav" height=2 width=2 autostart=true hidden=true loop=true>')
// --></SCRIPT>

If you have problems with MIDI files, be sure your server has the proper MIME types for MIDI files:

MIME Type Description Suffix/file extension
Audio/x-midi MIDI .mid
Audio/midi MIDI .mid

Display Problems

How can I prevent the colors in my page from being dithered?

You should use only the 216 colors in the standard palette supported by both Internet Explorer and Netscape Navigator to ensure that your page will look good on systems running in 256-color mode. These colors include any combination of red, green, and blue components of 0, 51, 102, 153, 204, and 255 (hex 00, 33, 66, 99, CC, and FF). The following graphic shows all 216 colors:

216 colors

How can I resize a control when the window is resized?

Place the control in a frame of the desired size, with WIDTH="100%" and HEIGHT="100%".

Why does a dot appear after an image?

A dot appears after an image if there is white space after the <IMAGE> tags in an anchor. This can come from a space like this:

<A HREF="some.htm"><IMG SOURCE="some.gif"> </A>

It will also happen if the anchor is split across two lines, like this:

<A HREF="some.long.URL.htm" TARGET="_top"><IMG SRC="some.gif">
</A>

How can I get rid of the gray box that appears while loading the Layout control?

Simply place a WIDTH=0 inside the HTML Layout Control Object tag:

<OBJECT CLASSID="CLSID:812AE312-8B8E-11CF-93C8-00AA00C08FDF"
ID="c" width=0 STYLE="LEFT:0;TOP:0">
</OBJECT>
Note: The HTML Layout Control technology, originally released with Internet Explorer 3.0, is now natively supported by Internet Explorer 4.0. Please see the HTML Layout Control home page for further information.

What screen resolution should I design for?

Surveys indicate that the great majority of users operate in 640x480 resolution with 256 colors. However, you should always try to find out the requirements of your target audience and base your design on that data. For example, if you are trying to sell high-end technology to power users, you can count on different requirements.

You should always view your site in the widest possible range of screen resolutions and color depths. If there is a problem under some configurations, you will need to fix it before your users discover it. If you are running Windows 95, be sure to install the QuickRes PowerToy so you can change resolutions and color depths easily. The PowerToys are currently at http://www.microsoft.com/windows95/downloads/contents/wutoys/w95pwrtoysset/default.asp?site=95 Non-MSDN Online Link.

How can I determine the user's screen resolution?

There aren't any general automated solutions to this. Different versions of Internet Explorer may provide the screen resolution or the window size in different ways. Other browsers do not provide either measurement. Many users with systems operating in high resolutions prefer to keep the browser covering just a portion of the screen. Thus the window size can be any value, not just one of the standard screen sizes. In practice it is rarely if ever practical to provide HTML pages based on the window size because of the range of possibilities. If you cannot design the page to gracefully adjust to different sizes, you should either design for a single size (normally 640x480) or provide links that allow the user to choose. These links could easily use script to open a new window of the appropriate size containing the corresponding page.

Links

How do I redirect a user to a new URL?

The following example displays a line of text for three seconds before automatically jumping to a new URL. Note that the quotes around the CONTENTS value must surround both the time delay and the target URL. The delay can be zero, but remember that the page will still be visible until the new page is downloaded.

<HTML>
<HEAD>
<TITLE>Old page</TITLE>
</HEAD>
<BODY BGCOLOR=#FFFFFF TEXT=#000040>
<META HTTP-EQUIV="REFRESH" CONTENT="3; URL=newpage.htm">
<FONT FACE="ARIAL" SIZE=3>
<i>We've moved!  I'll take you to our new page now...</i>
<BR>
</FONT>
</BODY>
</HTML>

Why don't my links to a section within a page work?

The NAME value is case sensitive. You must use the same form when it's defined and when it's referenced. These will work:

<A NAME="Section3">
<A HREF="#Section3">
<A HREF="page2#Section3">
These won't work:

<A NAME="Section3">
<A HREF="#section3">
<A HREF="page2#section3">

How can I describe a link in the status bar when the mouse points to an image?

Include a simple JScript in the anchor, like this:

<a href="main.html" target="main" onMouseOver="window.status='Back to the first 
page'; return true"><img src="home.gif" alt="home" border=0 
hspace=0 vspace=0 ></a><br>

Other Topics

How can I keep my page from being cached?

To keep your page from being cached (for example, if your content is dynamic and determined by a server application), use the <META> tag as follows:

<META HTTP-EQUIV="Expires" CONTENT="Tue, 04 Dec 1993 21:29:02 GMT">

Note that the expiration date should be already past. <META> tags are used in the <HEAD> section of the HTML page. Refer to http://www.w3.org/pub/WWW/Protocols/HTTP/1.1/spec.html Non-MS link for further details. Internet Explorer does not support HTTP-EQUIV Pragma no-cache.

How can I display small animations in my page?

There are currently two ways to display animations: using AVI files and animated GIFs.

How can I display a watermark?

Use the following code:

<BODY BACKGROUND="myimage.gif" BGPROPERTIES=FIXED>

How can I embed a document or spreadsheet in the middle of my page?

Use a floating frame, for example:

<IFRAME WIDTH="75%" HEIGHT="55%" NAME="fframe" SRC="hlsimple.doc">
   <FRAME WIDTH="75%" HEIGHT="55%" NAME="fframe" SRC="hlsimple.doc">
   <EMBED SRC="hlsimple.doc" width=200 height=100>
</IFRAME>

To view the embedded document or spreadsheet, the users must have the appropriate application installed. To open Hlsimple.doc in the example above, they will need Microsoft Word or Word Viewer, so it may be appropriate to provide a link to http://www.microsoft.com to download a viewer. Viewers are available for Microsoft Word, Microsoft Excel, and Microsoft PowerPoint®. You can also convert the document, spreadsheet, or presentation to HTML using appropriate Internet Assistant add-ons. The resulting HTML files may require further enhancements (for example, you may need to use style sheets to retain the original appearance). These HTML files can also be displayed in floating frames as shown above.

Why is a parameter in one of my tags being ignored?

A parameter value that contains non-numeric characters must always be enclosed in quotes. Thus, if you specify size in percentages, you must use quotes (for example, WIDTH="50%"). This rule also applies to any other parameters with non-numeric values, such as HREF. Some browsers will accept some of these values without quotes, but don't count on this always working properly.

How can I start my favorite HTML editor within Internet Explorer?

Although you can't change the program started by the View Source menu item, you can add a customized Edit command button like this:
  1. Open Internet Explorer.
  2. From the View menu, select Options.
  3. Click the Programs tab.
  4. Click the File Types button.
  5. Select "Internet Document (HTML)" in the list box.
  6. Click Edit.
  7. If an action named Edit is listed, select it and click the Edit button, then proceed to step 10 below.
  8. Click New.
  9. Type Edit in the Action field.
  10. Enter the command line needed to execute your desired editor in the Application used to perform action field. You need the full path to the executable file, so it's easiest to use Browse to locate it. Most editors require "%1" (including the quotes) after the file name.
  11. Click OK or Close as needed to close all open dialog boxes.
  12. Exit and restart Internet Explorer.

How can I display a message while an ActiveX control is downloading?

You can display a message in the space allocated to an object using the STANDBY parameter in the <OBJECT> tag, such as this example:

<OBJECT ID="Menu" WIDTH=200 HEIGHT=400
standby="Downloading the menu control… Please Wait"
CLASSID="…">


Frequently Asked Questions about the Dynamic HTML Editing Component

For Internet Explorer 5

Mark Davis and Rick Jesse
DHTML Editing Component Support and Development Team

Updated: March 12, 1999

What is the Dynamic HTML Editing Component?

The Microsoft Dynamic HTML (DHTML) Editing Component allows Web authors and application developers to add WYSIWYG DHTML editing capabilities to their Web sites and applications. The editing component uses Microsoft's Component Object Model (COM) technology to provide access to editing services such as basic HTML formatting, tables, undo/redo, find, and absolute positioning.

The DHTML Editing Component uses Internet Explorer to render HTML, so the editing environment is always in sync with the browsing environment. Web authors and developers can use any language, including Visual Basic, VBScript, JScript, C, C++, and Java to access editing services and provide a user interface for editing features. The DHTML Editing Component allows you to offer the following features:

Web authors and developers can also access the Document Object Model (DOM) to add sophisticated, custom editing features to their applications. In addition, you can edit pages created with Active Server Pages technology seamlessly, without changing the original server script. If you begin with existing HTML, the DHTML Editing Component will preserve your original formatting (the original white space and tags will remain).

Two types of components are available: the DHTML Editing DocObject and the DHTML Editing ActiveX control. The ActiveX control provides many high-level features and can be used from development environments such as Visual Basic, Visual J++ and Visual C++.

Who would benefit from using this component?

In addition to HTML authoring, Help, and e-mail applications, any Win32® application that edits or outputs HTML could use the editing component for rich formatting or easy layout. In addition, corporate developers can include this control in their Visual Basic applications to build HTML-based forms for their application front-ends.

Where can software vendors obtain the component?

The DHTML Editing Component is a system component in Microsoft Internet Explorer 5. If you have Internet Explorer 5 installed, you can develop applications, and you can deploy them to users who also have Internet Explorer 5.

If you will be deploying applications to users who are still using Internet Explorer 4, you can use an earlier version of the DHTML Editing Component, which is available as a downloadable SDK from here.

Where can I learn more about the DHTML Editing Component?

See the Features page for a full list of features. For a developer's perspective on the DHTML Editing Component, read DHTML Editing Made Easy by Nancy Cluts, also on this site.

You can also work with sample applications that illustrate the DHTML Editing Component. To get the samples, visit the MSDN Online Web Workshop Samples site. Display the table of contents (TOC), open the node for Reusing Browser Technology, and then select the sample called DHTML Editing Control. The Gallery contains a live sample that you can run directly as a Web application. It also offers a downloadable file that contains additional samples that illustrate how to use the DHTML Editing Component in Visual Basic and C-based applications.

Where can I learn more about Dynamic HTML?

The key things you need to learn to become fluent in Dynamic HTML are the Dynamic HTML Object Model (DOM) and Cascading Style Sheets (CSS). See the DHTML, HTML & CSS area of the MSDN Online Web Workshop for overviews and detailed information about DHTML, CSS, and the DOM. For detailed specs on DHTML, DOM and CSS, visit the World Wide Web Consortium Web site Non-MS link).

How do I use the DHTML Editing control?

The following HTML fragment shows how to insert the DHTML Editing control into a Web page:

<OBJECT
   CLASSID="clsid:2D360200-FFF5-11D1-8D03-00A0C959BC0A"
   ID=DHTMLEdit
   HEIGHT=400
   WIDTH=500>
</OBJECT>

Note the use of the ID attribute, which allows the control to be accessed by name. If you are using the control in a Visual Basic application, you can add the control as a component (named "DHTML Edit Control for IE5") to your project and it will be available in the component toolbox. For examples of how to use the control, see the Visual Basic sample VBEdit and the Web sample HelloWld, both available for download from the MSDN Online Web Workshop Samples site.

If you are hosting the control in a Microsoft Foundation Classes (MFC) application, insert the control into the project. A wrapper class for the control will be placed in your project and will be available in the resource editor. Either place the control on a dialog resource or create the control dynamically.

How do I load HTML into the component from memory?

The DHTML Editing control's DocumentHTML property provides access to the contents of the currently loaded document. You can assign a BSTR containing HTML to the DocumentHTML property to load HTML from memory.

If you are using the DocObject, you must create a Stream from an HGLOBAL and use the IPersistStreamInit::Load method. Please see the documentation for more information on using IPersistStreamInit. See the HelloWld Web sample, available for download from the MSDN Online Web Workshop Samples site, for an example of how to load HTML using the control's DocumentHTML property.

How do I access the Internet Explorer Document Object Model from the DHTML Editing Component?

The DHTML Editing control provides access to the underlying Internet Explorer Document Object Model through the DOM property. This property returns the Document object of the currently loaded Web page. The following JavaScript function demonstrates how to do this:

function ShowAll()
{
  dom = DHTMLEdit.DOM;
  len = dom.all.length;

  str = "";
  for ( i=0; i<len; i++ )
    str += dom.all[i].tagName + "\n";
  alert( str );
}

You can access the DOM from the DocObject by calling QueryInterface on the DocObject's IUnknown interface specifying IID_IHTMLDocument2:
IHTMLDocument2* pDom = NULL;
lpUnk->QueryInterface(IID_IHTMLDocument2, (void **) &pDom);

How do I insert new elements into a document?

Many commands are available that allow you to insert new HTML elements and apply formatting to existing HTML. They are invoked by calling the ExecCommand method with the appropriate command ID. Please refer to the documentation for the comprehensive set of available commands. The following HTML demonstrates how to insert a table with default values:

  
<SCRIPT LANGUAGE=JavaScript SRC="DHTMLEd.js">
   <!--
    Include the command IDs for ExecCommand. To get this include file,
download the samples from http://msdn.microsoft.com/downloads/samples/
   -->
</SCRIPT>

<SCRIPT LANGUAGE=JavaScript>
  function insertTable()
  {
    DHTMLEdit.ExecCommand(DECMD_INSERTTABLE,
                          OLECMDEXECOPT_DONTPROMPTUSER,
                          tableInfo);
  }
</SCRIPT>

<OBJECT ID=tableInfo 
   CLASSID="clsid:47B0DFC7-B7A3-11D1-ADC5-006008A5848C">
  <--
    create the tableInfo object
    give it an ID so you can reference
    it in the insertTable function
  &--gt;
</OBJECT>

You can also insert new HTML elements by accessing the Internet Explorer Document Object Model. The exact method will depend on how you want to insert the HTML. If you need to insert HTML elements relative to an existing element, the insertAdjacentHTML method is available on all elements. If you are replacing the user selection, you can create a TextRange object and call the pasteHTML method. This method can also be used to insert HTML at the current insertion point (caret). If you are modifying the HTML of an existing element, you can set the innerHTML or outerHTML properties, which are available on all elements. Note that the innerHTML property is only supported on block elements.

How do I insert script into the document?

To insert a script element into a document, use the following technique:

Dim scriptElement As String

' The script in the element inserted below will be executed
' when the DHTMLEdit control's DocumentComplete event fires.
' It will display a modal dialog box displaying the string
' "Document Loaded!"

scriptElement = "<body> <script for=editor
event=""DocumentComplete()""> 
alert(""Document Loaded!"");" </script>"

' Now inject the script into the document
DHTMLEdit1.DOM.body.insertAdjacentHTML "AfterBegin", scriptElement

If the DHTML Editing control's SaveDocument method is called after executing this code, you'll see that the <SCRIPT> element is the first element after the initial <BODY> tag.

How do I use ExecCommand and QueryStatus?

The ExecCommand method takes a numeric command ID and optional arguments, and typically operates on the current selection. QueryStatus is used to determine if a given command is valid for the current selection. ExecCommand and QueryStatus simplify the code necessary to update the user interface in your application. Use QueryStatus to enable and disable toolbars and menus; use ExecCommand to execute a command from a toolbar or menu.

How do I update my application's menus and toolbars based on the current selection?

The DHTML Editing control fires the DisplayChanged event whenever the editing context has changed (for example, when the user has selected an element or even just moved the cursor). Use this event to update your menus and toolbars by calling the QueryStatus method. To see an example of how to use the DisplayChanged event, see the VBEdit sample, available for download from the MSDN Online Web Workshop Samples site.

How do I implement my own commands?

The Document Object Model (DOM) is the primary Application Programming Interface (API) for modifying a document. If no command ID is available for an operation you want to provide in your application, implement the functionality by using the DOM. You can use the DOM to insert and remove HTML elements and modify existing elements using element properties or the CSS Object Model.

How do I obtain the currently selected text?

The current selection is accessed through the DOM's Selection object. The Selection object has a type property that returns a value of "None," "Text," or "Control." If the type is "Text," you can call the Selection object's createRange method to obtain a TextRange object corresponding to the selection. The text can then be accessed through the TextRange object's text and htmlText properties. The following JavaScript function demonstrates this:

function ShowSelection()
{
  sel = DHTMLEdit.DOM.selection;

  if ( "Text" == sel.type )
  {
    range = sel.createRange();
    alert( range.htmlText );
  }
  else
    alert( "No text selected" );
}

How do I find the selected element or the element under the insertion point?

The following is a an example of how to use the DOM Selection and TextRange objects to retrieve the selected element or the element directly under the insertion point:

' Assuming you have the DHTMLEdit control on
' a Visual Basic form and the control's name is DHTMLEdit1 ...

' Note that you should check the type of the selection.
' The Selection object's property "type" can return three values:

' "None" - nothing is selected (just blinking cursor)
' "Text" - text or mixed text is selected
' "Control" - a form control or image is selected

Private Sub GetElementUnderInsertionPoint()
  Dim rg As IHTMLTxtRange
  Dim ctlRg As IHTMLControlRange

  ' branch on the type of selection and
  ' get the element under the caret or the site selected object
  ' print its outerHTML

  Select Case DHTMLEdit1.DOM.selection.Type

    Case "None", "Text"

      Set rg = DHTMLEdit1.DOM.selection.createRange

      ' Collapse the range so that the scope of the
      ' range of the selection is the caret. That way the
      ' parentElement method will return the element directly
      ' under the caret. If you don't want to change the state of the
      ' selection, then duplicate the range and collapse it

      rg.collapse
      MsgBox rg.parentElement.outerHTML

    Case "Control"
      ' an element is site selected

      Set ctlRg = DHTMLEdit1.DOM.selection.createRange

      ' There can only be one site selected element at a time so the
      ' commonParentElement will return the site selected element

      MsgBox ctlRg.commonParentElement.outerHTML

  End Select
End Sub

How do I programatically set the position of the insertion point?

You can set the location of the insertion point programmatically by using the TextRange object. The following code demonstrates how to set the insertion point at the end of the document:

' Assuming you have the DHTMLEdit control on
' a Visual Basic form and the control's name is DHTMLEdit1 ...
Dim range As IHTMLTxtRange

Set range = DHTMLEdit1.DOM.body.createTextRange()
range.collapse False
range.Select

How do I trap an event such as ondoubleclick?

The DHTML Editing control provides events for the mouse and keyboard. You can also sink events for specific elements in a document. For an example of how to sink document events in C++, see the CEdit sample available for download at the MSDN Online Web Workshop Samples site.

How do I sink document object model events in Visual Basic?

You can sink DOM events in Visual Basic using the WithEvents statement. You must include a reference in your Visual Basic project to MSHTML.TLB. See the VBDom sample available for download at the MSDN Online Web Workshop Samples site for an example of how to sink various DOM events on the document and specific elements in a document.

How can I make a portion of a document read-only (non-editable)?

Sink the document's onkeydown event. In the onkeydown event handler, examine the element under the insertion point and if you want this element to be read-only, set the event object's returnValue property to False. This will cancel the onkeydown event, and the onkeypress and onkeyup events will not fire.

' Assuming you have the DHTMLEdit control on
' a Visual Basic form and the control's name is DHTMLEdit1 ...
Dim WithEvents docEvents As DHTMLDocument

Private Sub DHTMLEdit1_DocumentComplete()
' Sink the document's events
Set docEvents = DHTMLEdit1.DOM
End Sub

Private Sub docEvents_onkeydown()
' Make the entire document read-only
' This disables all keyboard input into the current document
' including the delete and arrow keys
DHTMLEdit1.DOM.parentWindow.event.returnValue = False
End Sub

Why does my onclick event handler never get called?

The onclick event does not fire in edit mode for the document object exposed through the control's DOM property, or any other HTML element within the document. However, the DHTML Editing control provides an onclick event handler that fires when the document or other elements are clicked. Developers can handle the onclick event and find the element under the insertion point in their event handler.

Why won't my VBScript events fire when I script them with Visual InterDev?

When you add the DHTML Editing control onto a page in Visual InterDev, code is generated that resembles the following (the OBJECT tag parameters have been excluded for clarity):

<HTML>
<HEAD>
<META name=VI60_defaultClientScript content=VBScript>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<SCRIPT ID=clientEventHandlersVBS LANGUAGE=vbscript>
<!--

Sub DHTMLSafe1_ShowContextMenu
MsgBox "ShowContextMenu"
End Sub

-->
</SCRIPT>
</HEAD>
<BODY>

<P>
<OBJECT classid=clsid:2D360201-FFF5-11D1-8D03-00A0C959BC0A id=DHTMLSafe1></OBJECT>
</P>

</BODY>
</HTML>

To make this code work, you must insert parameters for any events which take them. The following example shows the parameters added to the ShowContextMenu event handler.

<HTML>
<HEAD>
<META name=VI60_defaultClientScript content=VBScript>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<SCRIPT ID=clientEventHandlersVBS LANGUAGE=vbscript>
<!--

Sub DHTMLSafe1_ShowContextMenu(x,y)
MsgBox "ShowContextMenu " & x & ", " & y
End Sub

-->
</SCRIPT>
</HEAD>
<BODY>

<!-- etc -->

The parameters are part of the event signature in VBScript and are not optional. (In JScript they are optional.)

How do I display a shortcut menu?

When the user right-clicks within the DHTML Editing control's window, the ShowContextMenu event is fired. You can handle this event and provide a shortcut menu by calling the control's SetContextMenu method. If the user selects a menu item, the ContextMenuAction is fired, indicating which item was chosen. The following JavaScript event handlers demonstrate this:

<SCRIPT LANGUAGE=JavaScript SRC="DHTMLEd.js">
</SCRIPT>

<SCRIPT LANGUAGE=JavaScript FOR=DHTMLEdit EVENT=ShowContextMenu(x,y)>
  menuStrings = new Array();
  menuStates = new Array();

  menuStrings[0] = "Grayed item";
  menuStrings[1] = "Checked item";
  menuStrings[2] = "Unchecked item";
  menuStates[0] = OLE_TRISTATE_GRAY;
  menuStates[1] = OLE_TRISTATE_CHECKED;
  menuStates[2] = OLE_TRISTATE_UNCHECKED;

  DHTMLEdit.SetContextMenu( menuStrings, menuStates );
</SCRIPT>

<SCRIPT LANGUAGE=JavaScript FOR=DHTMLEdit EVENT=ContextMenuAction(itemIndex)>
  alert( "You selected item " + itemIndex );
</SCRIPT>

How can I remove the underline from a hyperlink?

The appearance of hyperlinks and other elements can be controlled through CSS attributes. The following is an example of a style sheet that removes the underline for all hyperlinks in a document:

<STYLE>
  A {
    text-decoration: none;
  }
</STYLE>

You can override a style sheet by using inline styles on specific elements. For example, to remove the underline from a specific hyperlink, you could set the style attribute of the Anchor as follows:

<A href="http://www.microsoft.com" 
  style="text-decoration: none">Look, no underline!</A>

Does the DHTML Editing Component support drag-and-drop from an external source?

The DHTML Editing DocObject and control register themselves as drop targets for the Clipboard format CF_HTML. When a drag operation is in progress involving this Clipboard format and the mouse is released on the DHTML Editing Component's window, the component will inject the HTML from the drop source's IDataObject into the current document at the point where the mouse is released. If the control's AbsoluteDropMode property is set and the HTML is capable of being absolutely positioned (such as with a table or button element), the HTML will be absolutely positioned. This is useful if you have implemented a toolbox or control palette and you are dragging controls onto the DHTML Editing control. For an example of implementing drag and drop, see the HTMLDrop example, available for download at the MSDN Online Web Workshop Samples site.

How can I receive drop notifications?

To participate in a drag/drop operation and receive drop notifications, you must host the DocObject and implement the IDocHostUIHandler::GetDropTarget method. See the Microsoft SiteBuilder Network Workshop for more information on the IDocHostUIHandler interface.

How do I print programmatically?

You can print the current document in the DHTML Editing Control using the control's PrintDocument method. If you are hosting the DocObject, you can print a document using ExecCommand and the command IDM_TRIED_PRINT.

What are the DESIGNTIMESP attributes that I see in an element's outerHTML?

The DHTML Editing Component uses a number of attributes internally to maintain document state during an editing session. These attributes are filtered out upon saving a document. However, if the outerHTML property of an element is accessed during an editing session, these attributes may be present. The DHTML Editing control provides the FilterSourceCode method for filtering these attributes from an arbitrary string of HTML. If you are using the DHTML Editing Component DocObject, you can use the FilterOut method with the dwFilterSourceCode flag.

How do I deploy the DHTML Editing Component with my application?

The DHTML Editing Component documentation provides information on how to deploy an application that is based around the DHTML Editing Component.


Back to topBack to top

© 1999 Microsoft Corporation. All rights reserved. Terms of use.