Microsoft HomeproductssearchsupportshopWrite Us   Microsoft Home
Magazine
 |  Community
 |  Workshop
 |  Tools & Samples
 |  Training
 |  Site Info

Workshop  |  DHTML, HTML & CSS

From Java Applet to Dynamic HTML


Ron Wodaski
Brad Merrill
Microsoft Corporation

June 15, 1998

DownloadDownload this document in Microsoft Word (.DOC) format (zipped, 16.1K).

Contents
Introduction
Overview of the Project
The Document Object Model
   Every Element Is an Object
   The DOM Event Model
   Events in the Document Object Model
Putting the Dynamic into HTML
   Dynamic Content
   Dynamic Styles
   Dynamic Positioning
Moving from Java to DHTML
   Test Cases
   What We Learned
   Making Choices
Performance Metrics
   Speed Is Good
   Comparative File Sizes
For Additional Information

Introduction

In this article, we convert sample applets in the Java Development Kit (JDK 1.1) to Dynamic HTML (DHTML) for the purpose of comparing user interface functionality. We found that DHMTL is a surprisingly fast and useful alternative to Java.

Back to topBack to top

Overview of the Project

The challenge -- born of a casual hallway conversation -- was to see whether DHTML could provide the same kinds of user interface functionality typically provided by Java applets. DHTML combines scripting and an extensive Document Object Model (DOM) to make the entire Web page interactive. We wondered what would happen if we converted Sunsoft's Java Development Kit (JDK) 1.1 sample applets into DHTML.

We began by converting the JDK animator sample to DHTML, using Visual Basic® Scripting Edition (VBScript). It proved to be an easy conversion, and the functionality was nearly identical to the Java version. We then recoded this and many of the remaining samples in JScript™. We found that VBScript and JScript were equally functional for converting from Java to DHTML.

The current HTML standard doesn't support drawing primitives (such as lines and circles), so we used ActiveX™ controls to provide those features as needed. We could have added those features using any language, however, because DHTML is language-independent. We selected a random mix of applets for conversion, ranging from those making no use of graphics to those making extensive use of graphics and sound.

After converting many of the JDK sample applets for the Windows 95 version of Internet Explorer 4.0, we began testing them on the Windows NT®, Windows 3.1, Macintosh, and Solaris versions of Internet Explorer. Most of the samples worked well across platforms without any modifications.

Our experiences converting the Java JDK samples to DHTML and JavaScript led us to several conclusions:

DHTML and Java can be integrated so that Java applets (or ActiveX controls) can interoperate and share information, using the DOM. From the developer's perspective, any embedded page object, no matter what language it's written in, can read from or write to the HTML page using the DOM. In the remainder of this article, you'll see examples that illustrate these points, and learn some of the mechanics of working with DHTML and Java.

Back to topBack to top

The Document Object Model

The heart of DHTML is the Document Object Model (DOM), which allows you to add an unprecedented level of interactivity to Web pages. The DOM used by Internet Explorer 4.0 isn't entirely new. Navigator 3. x and Internet Explorer 3. x use a limited object model based on the JavaScript object model. In that model, you can only change a limited number of objects, and only before the page displays. In the DOM used by Internet Explorer 4.0, everything on the page is an object, objects can be changed after the page loads, and the object model is language-independent.

Back to topBack to top

Every Element Is an Object

Every element on the Web page is now changeable, in real time, on the fly, on the client side. This means that you have substantial control over the appearance, content, and layout of a page while it is displayed in the browser. You usually do not need to reload a document to change it.

You can use the object model to interact with the properties, methods, and events of a Java applet, or you can access the DOM from within Java. This two-way communication gives Java the same access to the Web page content as any other language, allowing you to choose the tool you prefer for any given application. You can also host IE4/MSHTML, the rendering engine and parser portion of Internet Explorer 4.0, in your own applications using a variety of languages, providing the highest possible level of access to, and interactivity with, Web page content.

Objects are arranged in a hierarchy, and objects higher in the hierarchy contain the objects lower in the hierarchy. This makes it easy to either refer to an object by its ID, or to navigate through the hierarchy to locate the element you want to work with. The document object sits at the top of the hierarchy, with tags such as <DIV>, <P>, <B>, and <A> occupying various lower levels. This means, for example, you could read or write the contents of a link from Java, or add a handler to a <B> tag to control something in a Java applet.

Back to topBack to top

The DOM Event Model

The DOM brings a handy event model with it. Each event starts with a user action or condition. An event object is immediately updated with the conditions of the event (key pressed, mouse button clicked, coordinates of a click, data loaded from a database, and many more). Then the event fires, invoking any handler associated with the source element of the event.

Once the handler returns, the event bubbles to the next element in the object hierarchy (unless the event handler cancels bubbling). This continues until the final default action is carried out (unless an event handler cancels the default action).

For events that bubble, if there is no handler associated with the source element, the first element upward in the object hierarchy with a handler gets the event.

The events included in the object model are listed below, including keyboard, mouse, data binding, and other events. See the Internet Client SDK for more information about events and the event model. Two good starting points: Understanding the event model and detailed descriptions of events.

Back to topBack to top

Events in the Document Object Model

onabort onafterupdate onbeforeunload onbeforeupdate
onblur onbounce onchange onclick
ondataavailable ondatasetchanged ondatasetcomplete ondblclick
ondragstart onerror onerrorupdate onfilterchange
onfinish onfocus onhelp onkeydown
onkeypress onkeyup onload onmousedown
onmousemove onmouseout onmouseover onmouseup
onreadystatechange onreset onresize onrowenter
onrowexit onscroll onselect onselectstart
onstart onsubmit onunload  

Back to topBack to top

Putting the Dynamic into HTML

Dynamic HTML gets its name from the way it provides scripting access to the elements on a Web page. Previously, pages were static -- you could only write to the page before it was displayed using document.write(). With DHTML, you can alter just about anything on the page at any time. This reduces the need for round trips to the server when you want to display something new or different on the page - and it's accomplished by changing content, styles, and positions using script.

Back to topBack to top

Dynamic Content

All of the content on a Web page is accessible to the object model. You can replace a text string, or add a new picture to a page. You can change links dynamically, or add completely new content to large sections of a page. You can replace just the text of an element, or change the HTML. These operations are all very flexible, using the following properties and methods:

Properties:

innerText replaces the current content between the start and end tags with new content. Any HTML present is displayed as plain text. For example, if there is a section of text enclosed in bold tags, it will appear as text within <B> and </B> tags, like this:

This is some <B>bold text.</B>

innerHTML replaces the current content between the start and end tags with new content. Any HTML present is inserted as well, and will affect the appearance of the new content. For example, if there is a section of text enclosed in bold tags, it will appear as bold text, like this:

This is some bold text.

outerText is similar to the innerText property, but it removes the start and end tags as well as replacing the text.

outerHTML is similar to the innerHTML property, but it replaces the start and end tags as well as the content.

Methods:

InsertAdjacentText inserts new text before or after the beginning or end of an element. Any HTML tags present in the replacement content are displayed as plain text.

InsertAdjacentHTML inserts new HTML before or after the beginning (start tag) or end (end tag) of an element. Any HTML tags present in the replacement content are rendered as HTML.

For more complex requirements, you can use the Text Range object to do such things as:

You can use DHMTL to add new content to a Web page, to change existing content, and in many other ways. For example, you could scan the elements on the page and build a table of contents for the page dynamically, and then add the table of contents, including links, to the top or bottom of the page.

View the Nervous Text sample.

The Nervous Text sample uses dynamic content to set up the sample. First, a FOR loop puts each element of an array letters inside a <SPAN> tag, storing the result in a variable letSpan:

for (var i = 0; i < letlen; i++) {
letSpan += '<SPAN id=L'+i+' class="moveLetter">'+letters[i].let+'</SPAN>';
}

Then it writes the contents of the letSpan variable to the innerHTML property of a <DIV> with the ID theText:

theText.innerHTML = letSpan;

This puts a <SPAN> tag on the page for each element of the array:

<SPAN id=L0 class="moveLetter">H</SPAN>

If the contents of the array are changed, this process can be repeated to change the contents of the <DIV> at any time.

Back to topBack to top

Dynamic Styles

Cascading Styles Sheets (CSS) opens up the Web page to substantially more possibilities for formatting, font enhancements, and positioning. The DOM provides access to all of these features in scripts. This means that you can interactively set such attributes as font size, font weight, border color, border type, background color, text color, margin width, visibility, text decoration, and many more.

Script control of styles comes in three basic ways:

View the Blink sample.

For example, the Blink sample uses dynamic styles to change the color of text. Although a number of lines of mathematical calculation are required to determine what color to use, a single line of DHTML code is sufficient to set the text color for all of the text in an element:

o.style.color = r << 16 | g << 8 | b;

In this example, the object has the ID of "o," and the STYLE object is used to set the color property. The STYLE object has nearly 80 properties that you can set using script or CSS.

Back to topBack to top

Dynamic Positioning

Although positioning is accomplished using CSS technology, it's an important enough feature to be considered separately. There are two and a half dimensions associated with positioning. You can set the coordinates of an object on the page, resize objects, and you can also determine the stacking order of objects, using z-ordering.

Positioning is done with the top and left properties of the STYLE object. Resizing is accomplished with the width and height properties. Z-ordering uses the zIndex property.

There are two fundamental types of positioning:

Z-ordering allows you to stack objects on top of each other to achieve specific layouts. For example, you can stack text on top of a logo, or stack images on top of each other. You can change the stacking order by changing the zIndex property of one or more objects in script. An object with a higher zIndex is positioned above objects with a lower zIndex.

View the Bar Chart sample.

The Bar Chart sample makes extensive use of positioning. The bars are a group of two <DIV> statements, each using absolute positioning. They are stacked one above the other using Z ordering. For example, the top colored <DIV> has a zIndex of 1:

ochart.style.zIndex = 1;

while the shadow <DIV> uses a zIndex of zero:

ochart.style.zIndex = 0;

Each of the bars is positioned inside the gray <DIV> by setting the pixelTop and pixelLeft properties of its style object:

oshadow.style.pixelTop = curTop + sOffset;
oshadow.style.pixelLeft = lOffset + sOffset;

Back to topBack to top

Moving from Java to DHTML

We were able to duplicate the functionality of relatively simple Java applets using DHTML. The question naturally arises: Just how far can you go with DHTML? The key to the answer is the DOM, which isn't limited to scripting languages. You can develop with Java, scripting, and ActiveX in any combination. The DOM does establish scripting as a much more powerful development tool than it has been in the past. The question becomes when to use what tool. We therefore offer this short comparison of Java and scripting, examining the development environment and programming capabilities of each.

JavaScript and VBScript, the principal scripting tools for working with DHTML, are powerful tools, because they offer complete access to the DOM. Despite superficial similarities to Java, JavaScript has much more in common with other scripting languages, such as Perl, than it has with Java. Scripting languages generally do not support the features that Java programmers can count on. A Java programmer brings a certain set of assumptions to the table:

Scripting languages do not offer this level of control, but they are very flexible. Most of the functionality of Java can be duplicated in scripts, even while some of the key features of Java are completely absent. For example, JavaScript's expando properties can serve as a substitute for classes. The downside: JavaScript can refer to a non-existent property without generating an error. You can turn off expando properties (window.expando = false) to enforce name checking. VBScript, on the other hand, has built-in error-handling capabilities (on error resume next).

Solving real-world problems with scripts frequently requires a fundamentally different approach than you would use with Java. In the following test cases, you'll see specific examples of how we had to rethink a problem to solve it using DHTML. The bottom line is that scripting tools offer an ease of development that, in our opinion, makes DHTML the best choice for browser-oriented development.

Where does that leave Java? It's got great ability as a programming language, and it's useful as a middle-tier server language. It is most useful as a supplement to scripting tools, because it can supply functionality not currently included in HTML. The DOM makes it possible to use a variety of languages for Web development, including Java, Visual Basic, C, and C++.

Back to topBack to top

Test Cases

To give you an example of what it's like to move from Java to DHTML, let's look at a few examples. Three of the JDK samples provide a useful look at the transition process.

Card test

View the Card Test sample.

Description: The Card Test sample puts a bunch of buttons into a defined space, and then rearranges them in size and position when one of the buttons is clicked.

Java: Using Java, the basic approach is to create the necessary buttons, and to use six layout objects to define the six different button arrangements.

DHTML: With DHTML, we used expando properties on each button to define its location and size. The data for the arrangements are stored in six arrays, and these six arrays are then stored in an array to make it easy to access the data for each button in each arrangement. Event handlers for the buttons determine which arrangement to set.

The DHTML version starts with the btnData() function, which assigns expando properties to a button object:

function btnData(bTop, bLeft, bWidth, bHeight) {
  this.bTop    = bTop;
  this.bLeft   = bLeft;
  this.bWidth  = bWidth;
  this.bHeight = bHeight;
}

The data for each button arrangement is stored in an array:

var btn1List = new Array(
  new btnData(5, 100, 36, 24),
  new btnData(5, 140, 36, 24),
  new btnData(5, 180, 36, 24),
  new btnData(5, 220, 36, 24),
  new btnData(5, 260, 36, 24)
);

and these arrays are tucked into another array for easy reference:

var btnList = new Array(btn1List, btn2List, btn3List,
         btn4List, btn5List, btn6List);

When a button is clicked, its handler is invoked. The handler sets the global variable curBtn to the current button number, and the btnResize( ) function is called with a reference into the btnList array:

function firstClick() {
  curBtn = 0;
  btnResize(btnList[curBtn]);
}

The btnResize( ) function iterates through the objects in the array that is passed to it, setting the appropriate size and position for each button:

function btnResize(btndata) {
  for (var i = 0; i < btndata.length; i++) {
    var b = document.all("btn"+(i+1));
    b.style.top    = btndata[i].bTop;
    b.style.left   = btndata[i].bLeft;
    b.style.width  = btndata[i].bWidth;
    b.style.height = btndata[i].bHeight;
  }
}

This approach mimics the ability of Java to create an instance of an object, but it lacks the features of Java's class inheritance model. It's up to the programmer to create the structure needed to make the approach work.

Animator

View the Animator sample.

Description: The Animator sample loads 10 images, then displays them in sequence to create an animation.

Java: The Java version of this applet is very large (28K of source, including comments) and implements sophisticated features, such as double buffering, to provide the smoothest possible animation.

DHTML: The Dynamic HTML version is very compact (2K, including comments), relying on Internet Explorer 4.0 for most of the sophistication. The approach is to simply create 10 <IMG> tags, and then to display them in the correct order to create an animation.

We developed the DHTML code for this sample using an iterative process. The first version was implemented in VBScript, but VBScript wasn't yet supported on Internet Explorer 4.0 for the Macintosh. We converted to a JScript version that has a single <IMG> tag whose SRC property gets changed in the script, resulting in an animation.

This first version was very slow on some platforms. Most of the time was spent loading images, and the resulting animation looked awkward as each image displayed when it was downloaded, rather than at the correct time.

The next version, the one shown via the link above, writes 10 IMG elements to the page using document.write( ) in a for loop. Constructing the text for each <IMG> tag based on the current iteration of the loop varies the filename and ID of each IMG element.

The effect of this approach is to load all images before starting the animation: animation isn't begun until the document's onload event occurs, which isn't until the page, including the images, is completely loaded. Another approach would be to have a single <IMG>tag display the start of the animation, and to create the other nine IMG objects using the new operator after the page finishes loading. This has the advantage of displaying one image while the other images load.

Blink

View the Blink sample.

Description: The Blink sample changes the colors of words based on their position.

Java: The Java version calculates RGB values in a constrained range, then adds to that the text font size multiplied by the line the text occurs on.

DHTML: DHTML does not support font metrics, so we had to use some trickery to duplicate the calculations from the Java version. In addition, each of the words was tucked into its own <SPAN> tag for easy reference.

The math used to calculate colors was essentially the same in the Java and DHTML versions, but there was a substantial difference in the way the numbers fed into the calculations were determined.

The Java version determines the line on which a given word sits by iterating through the words (using a string tokenizer) and using the font object to get the line the text is on:

public void paint(Graphics g) {
  int x = 0, y = font.getSize(), space;
  int red = (int)(Math.random() * 50);
  int green = (int)(Math.random() * 50);
  int blue = (int)(Math.random() * 256);
  Dimension d = size();

  g.setColor(Color.black);
  g.setFont(font);
  FontMetrics fm = g.getFontMetrics();
  space = fm.stringWidth(" ");
  for (StringTokenizer t = new StringTokenizer(lbl);  t.hasMoreTokens() ; ) {
    String word = t.nextToken();
    int w = fm.stringWidth(word) + space;
    if (x + w > d.width) {
      x = 0;
      y += font.getSize();
    }
    if (Math.random() < 0.5) {
      g.setColor(new java.awt.Color((red + y * 30) % 256,
        (green + x / 3) % 256, blue));
    } else {
      g.setColor(getBackground());
    }
    g.drawString(word, x, y);
    x += w;
  }
}

The DHTML version gets the line the text is on by using the SPAN's offsetTop and offsetHeight properties:

function blinkWords() {
var red = Math.floor(Math.random()*50);
var green = Math.floor(Math.random()*50);
var blue = Math.floor(Math.random()*256);

for (var i = 0; i < NumWords; i++)
  {
  var o = document.all("TXT"+i);
  if (Math.random() < 0.5)
    {
    var r = Math.floor(red+(24*((o.offsetTop+o.offsetHeight)/o.offsetHeight))
      *30)%256;
    var g = Math.floor(green + o.offsetLeft/3) % 256;
    var b = (blue);
    o.style.color = r << 16 | g << 8 | b;
    }
  else
    {
    o.style.color = "#d3d3d3";
    }
  }
}

Back to topBack to top

What We Learned

The Java developer who approaches JavaScript (and scripting in general) should be wary of preconceptions. Some gotchas that we encountered were:

On the other hand, we couldn't easily do some things, such as graphics, since DHTML doesn't support primitive graphics or font metrics on all platforms. This leads to a natural marriage: DHTML excels at the task of communicating with and manipulating the Web page, and controls naturally fill in wherever DHTML hits a boundary. For example, DirectAnimation and ActiveMovie are two technologies already in place for the Win32 platform, and Java (or C++ or Visual Basic) serve as good tools for developing additional extensions, especially if they adhere to and take advantage of the DOM.

A few other compromises were involved in using a scripting language instead of Java. Debugging capabilities are less sophisticated in DHTML, but there is a script debugger. You can elect to have the script debugger invoked automatically when an error occurs, displaying an error message and the line number that caused the error. If you use this method, you have to give yourself some hints, such as using alert( ) to display values of variables. This can be dangerous, because you can't conveniently kill an Internet Explorer 4.0 session during an alert if you accidentally create an infinite loop.

Fortunately (although we discovered this too late to be of much help), you can also run a DHTML page from the script debugger, and use the debugger to set break points and examine variables. This is the preferred approach.

Back to topBack to top

Making Choices

Key points to consider when deciding which tools to use to develop for the Web:

Back to topBack to top

Performance Metrics

After we completed the DHTML versions of the JDK samples, we were curious to know how well they performed against the Java versions. In most respects, the DHTML versions were faster.

Speed Is Good

One of the first things evident when comparing the Java and Dynamic HTML samples was the difference in the time it took for the applications to download and initialize. We ran several timing tests to find out the exact nature of the difference. The full results are shown in Table 1.

We timed five different samples five times each to see how long they took to download, initialize, and display (see table below). The Java applets took an average of 2.75 seconds (69 seconds total divided by 25). The DHTML versions took an average of 1.75 seconds (44 seconds total). In other words, the DHTML versions became active 37 percent faster. This difference was small but noticeable for these simple samples. Since the more complex examples (such as Card Test) exhibited the greatest time difference, we project that larger examples would result in a more significant variance.

Several reasons for this became obvious during the time trials:

Load + initialization times

The following table shows the average number of seconds for each sample to download, initialize, and display:

Sample name Java average DHTML average Difference
Bar Chart 3 1.6 1.4
Blink 2.6 2 0.6
Card Test 3.6 1.6 2.0
Jumping Box 2.4 1.4 1.0
Nervous Text 2.2 2.2 0.0
Totals 2.75 1.75 1.0

Note: Trials were conducted over a 33.6K modem on a Pentium 200 computer running Windows NT 4.0. The timer was started when a link was clicked, and the timer was stopped when the applet or DHTML version was fully displayed and operational. We invite readers to do their own testing with these and other Java/DHTML samples to see the speed differences for themselves.

Back to topBack to top

Comparative File Sizes

Sample name Java DHTML Reduction %
Animator 18,671 960 17,711 94.86%
Bar Chart 6,321 5,742 579 9.16%
Blink 2,646 1,298 1,348 50.94%
Card Test 3,881 3,811 70 1.80%
Jumping Box 2,987 1,932 1,055 35.32%
Nervous Text 2,157 2,133 24 1.11%
Simple Graph 1,218 995 223 18.31%
Tic-Tac-Toe 3,653 7146 >-3,493 -95.62%
Image Map 32,288 4,434 27,854 86.27%
Spreadsheet 18,217 8,537 9,680 53.14%
Arc Test 4,496 3,611 885 19.68%
Overall Totals: 96,535 40,599 55,936 57.94%

Note: File sizes for Java applets reflect compiled code (the *.class files needed for the applet to do its job), plus HTML code needed to specify the applet and its parameters. File sizes for DHTML samples reflect all of the source code included in the sample.

Back to topBack to top

For Additional Information

Dynamic HTML

Document Object Model

VBScript Tutorial and Language Reference Non-SBN link

JScript Tutorial and Language Reference Non-SBN link


Did you find this article useful? Gripes? Compliments? Suggestions for other articles? Write us!

Back to topBack to top

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

 

Magazine Home
Ask Jane
DHTML Dude
Extreme XML
For Starters
More or Hess
Servin' It Up
Site Lights
Web Men Talking
Member Community Home
Benefits: Freebies & Discounts
Benefits: Promote Your Site
Benefits: Connect with Your Peers
Benefits at a Glance
Online Special-Interest Groups
Your Membership
SBN Stores
Join Now
Workshop Home
Essentials
Content & Component Delivery
Component Development
Data Access & Databases
Design
DHTML, HTML & CSS
Extensible Markup Language (XML)
Languages & Development Tools
Messaging & Collaboration
Networking, Protocols & Data Formats
Reusing Browser Technology
Security & Cryptography
Server Technologies
Streaming & Interactive Media
Web Content Management
Workshop Index
Tools & Samples Home
Tools
Samples, Headers, Libs
Images
Sounds
Style Sheets
Web Fonts
Training Home
SBN Live Seminars
SBN Live Chats
Courses
Peer Support
CD-ROM Training
Books & Training Kits
Certification
SBN Home
New to SBN?
What's New on SBN
Site Map
Site Search
Glossary
Write Us
About This Site