Overview of Dynamic HTML

Notes by P. Conrad for CISC103, Univ. of DE, Fall 2005

The basic idea

You make a web page that two kinds of elements:

  1. Static elements: ones that don't change
  2. Dynamic elements: ones whose content can change.

A simple introduction

A five-step plan for simple use of dynamic HTML

  1. Design a web page.
  2. Set the id attribute on the elements that will be dynamic
  3. In the JavaScript code, use getElementById to grab hold of those elements
  4. Set the content by setting the .innerHTML property.
  5. Set the style by setting subproperties of the .style property.

When does the element change?

When some event happens, for example:

  1. A mouse rollover
  2. Pressing a button
  3. A timer goes off

Typically, you write a function that changes the element. For example, suppose you had this exam question:

Write a function called July4thGreeeting() that:

  1. finds the element in the document with id attribute "thisOne"
  2. sets the color of that element to red
  3. changes the text of the element to "Happy Birthday America!"

Such a function might look like this:

 function July4thGreeting()
{
var theElementToChange = window.document.getElementById("thisOne");
theElementToChange.innerHTML = "Happy Birthday America!";
theElementToChange.style.color = "red";
}

Two things you can do with a span tag or div tag:

  1. You can set the id attribute: gives an element a name so that you can refer to it in JavaScript code
  2. You can set the style attribute: used to apply CSS properties to an element to change its visual appearance

That will most certainly be on the final exam.

The source code for this very document

If you look at the source code for this document, dynHTML.html, you'll see five global variables. The first two global variables are "arrays". In this case, they are arrays of string literals. The first array, colors, contains a list of color names. These color names need to be legal colors names for CSS properties. (A list of those color names is in one of the appendices of Deitel/Deitel/Goldberg book.)

The other array contains a list of synonyms for the word "change".

var colors = [ "red", "green", "blue", "purple", "black", 
                "brown", "orange", "darkgray"];
var differentTexts = ["change", "become different", 
                   "morph into something else","mutate",
				   "put on a new face","remake themselves"];

var curColor = 0;
var curText = 0;
var secondCounter = 1;