Computer Science Illuminated, Third Edition

eLearning

Animated Flashcards
Live Wire
Cryptic Crossword Puzzles
Ethical Issues
Biographical Sketches
Did You Know
Goin Live
Google Code Digital Lab Manual
Online Glossary
The Learning Store
Language Library
Download PEP/7
Instructor Resources
Student Resources

eLearning Home

Lab #13

Introduction to Dynamic HTML


13.1 What is Dynamic HTML?

Ready for a big secret?  DHTML stands for Dynamic HTML.  Actually, that's not really the secret.  The secret is that there is no DHTML!  DHTML really is a term for authoring a web page that includes both Cascading Style Sheets (CSS) and JavaScript.  So, if you've skipped over Labs 11 and 12, and don't know what CSS and JavaScript are, you should go back now and work through them.

If you haven't already, try moving your mouse over the link above.  When your mouse is over the link, the background of this web page changes color to a light green color (assuming you have a relatively recent web browser).  Then, when you move your mouse away from the link, the background returns to a cream color.  Welcome to DHTML.

To achieve this result (changing the background color via a mouse event), we combined the ability to execute a JavaScript function when a mouse event occurs on a link tag (mousing over and mousing away are JavaScript events we can trap for), with the ability to set the background color of a web page (a feature of Cascading Style Sheets).  We will show you additional tricks and things to add to your web pages in the remaining sections of this lab.

13.2 Getting Started with DHTML

To get started with DHTML we will detail how we achieved the background color change effect shown via the link above.  To start with, we created the paragraph and link as one normally would.  However, the anchor tag (<a>) included two new attributes that we have not covered before.  The new attributes are onMouseOver and onMouseOut and they each can be used to call a JavaScript function when the specified event occurs.  The final version of the anchor tag appears as:
<a href="index.html" onMouseOver="setBackground()" onMouseOut="revertBackground()">back now</a>
Here, the onMouseOver attribute is used to call the JavaScript function setBackground, while the onMouseOut attribute is used to call the revertBackground function.  There are several other attributes that can handle events for the anchor tag as well.  They are summarized in the table below.

Attribute (Event)
Description
onMouseDown
handles when the user depresses the mouse button
onMouseUp
handles when the user releases the mouse button
onClick
handles when the user performs a single click event (with the mouse)
onDoubleClick
handles when the user performs a double click event (with the mouse)

That brings us to the function.  We created two very simple functions that were called when the user moves the mouse over and away from the link.  These are the setBackground and revertBackground functions respectively.  Their definition occurs in a JavaScript block in the page's header.  The entire JavaScript portion of the page is duplicated in the following table:

added JavaScript defining the setBackground and revertBackground functions
<script language="JavaScript">
   function setBackground(){
      document.body.style.backgroundcolor="#88CCCC";
   }

   function revertBackground() {
      document.body.style.backgroundcolor="#ffffee";
   }
</script>

Both functions perform the same task with different results.  Each of the functions set the background color of the web page to a specified value.  To achieve this result, we will apply the color setting through the manipulation of the document object.  More specifically, we will refer to the document object's body object, and then reference the style object.  From there, we apply our color setting to the backgroundColor object.

Another way of saying the same thing is this: "The document object contains the body object, which contains the style object, which contains the backgroundColor object.  The modification of the value of the backgroundColor object permits us to change the background color of the current web page".

What we really are describing here is the document object model used by the web browser and JavaScript.  The model (also known as the DOM) is rather large and contains too much to cover here.  However, if you do further work with DHTML and JavaScript, you will likely be interested in learning more about the DOM.

Lab Activity #1:
  1. Find a good on-line reference to the DOM.  What is the URL of the reference you have located? _______________________________

  2. Incorporate some of the other events listed in the table above into your web pages.  For the most part, each of them may be applied as an attribute to a document, button or link.

    (Hint: to apply the event to the document, place the event's attribute in the body tag of the document.)  Try creating a JavaScript alert, or updating a clock display (like the one created in Lab 12).

13.3 Monitoring Mouse Movements

As we have seen from the previous section, there are a variety of mouse events that we can capture - thereby enabling us to be able to perform a specific task when an event occurs.  Let's add another to the list: onMouseMove.  More specifically, we would like to display the X and Y coordinates of the mouse's location in document window as the user moves the mouse.  However, we would like to stay away from an HTML form, but display the coordinates with ordinary HTML text.  (Recall that we used an HTML form in Lab 12 when we created our updating clock.)

Let's assume we have a simple web page that looks like what is shown in Figure 1.  The code used to produce the page follows the image.

The initial appearance of our page.
Figure 1: The initial appearance of our page.

dhtml1.html
<html>
<head>

    <title>DHTML Demo</title>
</head>

<body>
    <center><h3>
Welcome to CSIlluminated!</h3>
    The mouse is at the location:
    <p id="mouseLoc">0, 0</p>
    </center>
   
</body>
</html>


Notice the use of the id attribute in the paragraph tag.  We will use this attribute in our JavaScript to edit the contents of the paragraph tag.  Initially, the contents are set to the value "0, 0" which indicates that the mouse coordinates X and Y (where X indicates the pixel distance from the left side of the window that the document is rendered, and Y indicates the distance in pixels from the top of the window where the document is rendered).

We will modify the body tag to call a JavaScript function to update the contents of the mouseLoc paragraph tag.  To achieve this, we will add the onMouseMove attribute as follows:
<body onMouseMove="display('mouseLoc', event);">
Each time the mouse is moved within the body of the HTML document, we call the display function and pass it two arguments.  The first is the ID name of the HTML element we wish to manipulate (in this case the mouseLoc paragraph), and the second argument is the actual mouse event object (which contains information about the location of the mouse among other things).

We add to the header of the document the display function which is quite small.  Its code is as follows:
    <script language="JavaScript">
    function display(ident, eventObject) {
        var element;
       
        element = document.getElementById(ident);
        element.innerHTML = eventObject.clientX + ", " + eventObject.clientY;
    }
    </script>
The function declares a variable (element) which we will use to manipulate the desired text.  Then, we obtain a reference to the paragraph tag which is specified in the ident parameter.  To obtain the reference, we use the document.getElementById() function and pass it the value stored in the ident parameter.

Assuming there is an element in the document which has a matching ID attribute, we can then manipulate its contents by setting the innerHTML property.  In this case, we obtain the X location (horizontal) of the mouse pointer at the time of the event, and concatenate it with the string ", ".  We follow this concatenation with another, the value of the Y location (vertical) of the mouse pointer at the time of the event.

Because we are modifying the innerHTML property, the value we are setting can also contain HTML tags as well (such as <i>, <b>, etc.)  The innerHTML property helps to preserve their values and thus they are applied on the screen when the text modification is complete.

Our final page has the following source code:
dhtml1.html
<html>
<head>
    <title>
DHTML Demo</title>
    <script language="JavaScript">

    function display(ident, eventObject) {
        var element;
       
        element = document.getElementById(ident);
        element.innerHTML = eventObject.clientX + ", " + eventObject.clientY;
    }
    </script>
</head>

<body onMouseMove="display('mouseLoc', event);">

    <center><h3>Welcome to CSIlluminated!</h3>
    The mouse is at the location:
    <p id="mouseLoc">0, 0</p>
    </center>
   
</body>
</html>



Lab Activity #2:
  1. Add the example above to a new web page of your own.  However, rather than having one element which is manipulated (in our example the mouseLoc paragraph), separate the values into two separate elements on two lines.  Create a label for each, similar to the form of:
Mouse Location X: <x-value>
Mouse Location Y: <y-value>
  1. Modify the clock program demonstrated in Lab 12 to display its values without an HTML form.

  2. Modify the example above to display the mouse coordinates every 2 seconds.  (Hint: examine how the clock program updates its display!)

13.4 Magical Text

Let's take the example from Section 13.3 a bit further.  Rather than tracking the coordinates of the mouse, we would like to pop up a message or text when the mouse passes over an element.

More specifically, we will display the contents of a table when the mouse passes over a link in the document.  To achieve this, we first need the code for our table:
<table width="200" id="message" style="z-index: 5; visibility: hidden; border-width: thin; border-color: black; border-style: solid; position: absolute; left: 0; top: 0;">
   <tr><td>That site really <b>rocks</b>!</td></tr>
</table>
With this code, we create a table of size 200 which contains just one cell.  The content of the cell is the message "That site really rocks!"  If you look closely at the attributes of the table tag, you will likely see something new.  In addition to specifying the id attribute for the table itself, we have embedded a style attribute.  This is known as an in-line style.

The value assigned to this attribute is a string of CSS style properties which we are now somewhat familiar with.  However, there are a few new properties we have included in this example.  Briefly, each is described in the following table.

Property
Value
Description
visibility
hidden
Prevents an element from being rendered by the browser, yet preserves space for the element.
position
absolute
Positioning attribute which makes this element a block element (an element that will be rendered on its own line with definable margins both above and below the element) positions it relative to its parent element.
left
0
Defines the left edge for the box which contains this element relative to the left edge of the parent block element (such as a paragraph, list, heading, or table).
top
0
Defines the top edge of the box which contains this element relative to the top edge of the parent block element.
z-index
5
Defines the layering of the element relative to other content on the page.

Essentially what we have done is created a small table with one cell of text in it.  The table is placed with its upper left corner at the 0,0 coordinates in the browser window (as you will see the full code listing below, the parent element is the body tag).  The table has a thin black border around it, and is invisible.

The z-index provides a vertical quality to our web page which we have not seen before.  Layers can be created such that elements can be placed on top of each other.  This may be undesirable in some cases to have text layered over text, however, in this case, we want the table to appear above other text.  Thus, we have given it a value of 5.  The larger the value of the z-index, the closer the element is to the user (or so it appears).  The remaining text on the page will not have a z-index, and thus be rendered beneath the hidden table!

We complete the source code of the page by adding a new display function in the document's header.  In addition, we create a link on the page and tie the function to the onMouseOver event.  When the user mouses over the link, the table is displayed on top of anything else on the page.

We created the function similarly to the one shown in the previous section.  Both the id string and the event object are passed to the function, so that we can properly display the table.  We pass the id value so that we can obtain a reference to the table from within the function.  The event object is passed so that we can obtain the value of the mouse coordinates.  The source code is as follows:

dhtml2.html
<html>
<head>
    <title>
DHTML Demo</title>
    <script language="JavaScript">

    function display(ident, eventObject) {
        var element,
            mousePositionX,
            mousePositionY,
           
        element = document.getElementById(ident);
        mousePositionX = eventObject.clientX;
        mousePositionY = eventObject.clientY;
       
        element.style.left = mousePositionX + 30;
        element.style.top = mousePositionY + 30;
        element.style.visibility = "visible";
    }
    </script>
</head>

<body>
    <center><h3>
Welcome to CSIlluminated!</h3>
    Be sure to visit: <a href="http://csilluminated.jbpub.com" onMouseOver="display('message', event); return true;">csilluminated.jbpub.com</a>
    </center>
   
    <table width="200"
id="message" style="z-index: 5; visibility: hidden; border-width: thin; border-color: black; border-style: solid; position: absolute; left: 0; top: 0;">
        <tr><td>
That site really <b>rocks</b>!</td></tr>
    </table>

</body>
</html>


Once the function is called, we obtain the reference to the element and the mouse coordinates.  Before modifying the visibility property of the element (the table), we change the tables left and top properties so that the table will be 30 pixels to the right and below where the mouse event occurs.  Finally, we change the visibility property and display the table!  A picture of our popped up table is shown in Figure 2.

You may have noticed that we used the bold and centering formatting tags in this document.  We did this, rather than using CSS, so that we could place all of the code needed to create this page in one source code file.  We could have moved the formatting information to a separate CSS file, but chose not to in order to keep this example brief.
 
The hidden table is revealed!
Figure 2: The hidden table is revealed!

Lab Activity #3:
  1. Apply the example shown in this section to at least 5 links on your web pages. In each case, include additional textual information about the site you are linking to.  For example, add a sentence about how often you view the site, or what you use the site for.  Consider including your rating of each site with a scale of 1 to 5.

  2. Next, extend the example above to include a new function removeDisplay() which hides the table when the mouse moves away from the link.  Refer to Section 13.2 to determine the appropriate event you wish to handle.

  3. Finally, change the display of a site's rank to be graphic images rather than a textual value.  A series of star icons can be used for each value in the scale.

13.5 More with DHTML

We have only begun to touch on what you can do with DHTML.  In this lab, we have introduced parts of the document object that is part of the DOM.  Using the document object, we can examine and manipulate elements of the HTML document that the user is viewing.

The navigator object is another object that is a component of the DOM which you can also examine.  The navigator object deals with the web browser itself and permits us to obtain information about the user's browser.  This can be a powerful advantage when coding JavaScript and DHTML pages, since not every browser supports every property and method that the DOM is listing.  (Web developers will tell you that supporting the wide variety of browsers, with varying ages and functionality, is one of the hardest parts of their job.)

In the example below, we will display information about the user's browser in an alert message (similar to the alert we created in Lab 12.   The properties we will be accessing from the navigator object are listed in the table below, each with a short description.  It is important to remember that this is an incomplete list of properties.  One of the tasks for Lab Activity #4, you will be asked to list the properties and methods of the navigator object along with a short description.

Property
Description
appName
Provides the name of the web browser
appVersion
Provides the version information of the web browser
platform
Provides the name of the operating system that the browser is currently executing on.

Using these 3 properties, we can construct a simple yet informative message to the user, indicating what we know about their browser.  To do so, we create a shot HTML document with a body that contains the message "What we know about you!".  In the header of the document, we include the JavaScript necessary to create the alert message.  Our source code is listed in the following table, and a screen capture of the result is shown in FIgure 3.

dhtml3.html
<html>
    <head>
        <title>
DHTML Alert Demo</title>
        <script language="JavaScript">

            var Name = "Browser: " + navigator.appName;
            var Version = "Version: " + navigator.appVersion;
            var Platform = "Platform: " + navigator.platform;
           
            alert (Name + "\n" + Version + "\n" + Platform);
        </script>
    </head>
   
    <body>
        <center><h3>
What we know about you!</h3></center>
    </body>
</html>


Our informational alert message.
Figure 3: Our informational alert message.

In Figure 3, you can see that that message indicates we are using Netscape version 5.0 on the Linux platform.  However, in truth, we used Mozilla (created in part by developers at Netscape) version 1.0.  Keep in mind that when coding for the web, these discrepancies will be very common and sometimes frustrating to work with.  However, now that we know how to obtain the name and version of the browser (along with other information), we can create pages to deal with the more frustrating experience of browser versions which don't support certain JavaScript or CSS features.

Lab Activity #4:
  1. Use the DOM you found earlier Lab Activity #1 to list all of the core objects which you can access (hint: navigator is one of them).

  2. List all of the properties and methods that comprise the navigator object.  Provide a short description of each.

  3. Enhance the example message to create a web page that will provide as much information as possible to the user about their browser.  Do not display an alert, but rather place all information in the page itself.

About the labs:
These labs were developed in conjunction with the Jones and Bartlett textbook Computer Science Illuminated by Nell Dale and John Lewis.
ISBN:  0-7637-1760-6
Lab content developed by Pete DePasquale and John Lewis.

 
Educators: More Information About This Text Other Computer Science Titles at Jones and Bartlett
Copyright 2019 Jones and Bartlett PublishersContact webmaster