In this lesson, you will learn about the following: ● Defining Dynamic HTML and the technologies that make it possible ● Understanding the Document Object Model DOM ● Creating cross-brow
Trang 1Lesson 15 Creating Applications with Dynamic HTML and AJAX
Lesson 15 Creating Applications with Dynamic HTML and
AJAX
Dynamic HTML offers you something unique: the capability to make changes in web pages on the fly Using conventional HTML, web pages are loaded by a browser and just sit there until you click a link or interact with forms That's pretty simple, but it can be static and boring
People have improved upon static web pages by using a variety of technologies outside the realm of HTML Any number of platforms are available for creating server-side web applications You can embed Shockwave and Flash in your pages to add animation and interactivity, and use Java applets to provide application-like functions However, these methods rely on browser plug-ins or virtual machines (which can be messy), and can lead to longer download times
Dynamic HTML is different DHTML, as it is commonly known, enables you to create web pages that
look, feel, and act a lot like the other programs you use on your computerusing the web browser as an interfacewithout having to rely on external programming solutions AJAX takes that one step further, and allows you to actually exchange data with the server from within your web page, without submitting
a form or clicking on a link
In this Lesson
Today's lesson is a full plate of information, so let's get right to it In this lesson, you will learn about the following:
● Defining Dynamic HTML and the technologies that make it possible
● Understanding the Document Object Model (DOM)
● Creating cross-browser routines with DHTML by testing browser capabilities
● Examples of using DHTML to manipulate elements on a page
Trang 2What Exactly Is Dynamic HTML?
What Exactly Is Dynamic HTML?
Simply put, Dynamic HTML uses normal HTML elements to create a web page that relies on style sheets
for element formatting, and scripting to dynamically change HTML content, style, or positioning, without having to re-download the page from the server Dynamic HTML isn't a thing by itself, but a collection of
technologies working together to produce an interactive interface So, what can you do with DHTML? The possibilities are endless! Just to whet your appetite, here are a few of them:
● Move objects around the web page
● Show or hide elements
● Dynamically alter the color and size of web content
● Provide drag-and-drop functionality similar to that used by modern graphical operating systems (such as Windows and the Mac OS)
Dynamic HTML was born with the advent of the "fours." The World Wide Web Consortium developed HTML 4.01 and released the official recommendation at about the same time Microsoft and Netscape released their competing web browsers, Internet Explorer 4 and Netscape 4 There was a flurry of
activity surrounding all this HTML 4.01 promoted several new features to better integrate itself with cascading style sheets and respond to user events Microsoft and Netscape were competing hard for market share in the browser war, and the result of it all was a drive for something different: a level of user interactivity and "dynamism" in web pages that previously was impossible without resorting to
external programming DHTML was born
For DHTML to work, it requires the following three key technologies supported by the web browser:
● HTML
● Cascading style sheets
● Scripting
Style sheets are wonderful after you know how to use them, and are a critical component of DHTML Although DHTML technically isn't dependent on any one type of style sheet, the official W3C style sheet
technology, cascading style sheets (CSS), is the standard CSS enables you to format elements on your
web pages using properties, such as font, color, and spacing, as well as positioning items on the web page
DHTML takes style to a new level Rather than creating a style rule or positioning an element on the page and then forgetting about it, you can use DHTML to dynamically alter the visual style or position of your elements As with HTML, there are inconsistencies in how various browsers implement CSS None
have fully implemented all of the specifications, but also browsers have implemented portions
differently Things are a lot better now than they were a few years ago The latest versions of Internet Explorer, Netscape, and Opera offer much closer adherence to the HTML and CSS standards than they once did That said, complex dynamic HTML applications require lots of testing and many workarounds
to work on all the browsers that are still in common use
Finally, scripting is a sort of glue that holds together everything in DHTML Scripting is the engine that makes DHTML go Using scripting, you can alter the content on your page when the page loads in
response to any of the events discussed in Lesson 12, "Introducing JavaScript," or even when the user leaves the page
Caution
If you've caught on to the "inconsistent implementation across web browsers" pattern here,
Trang 3What Exactly Is Dynamic HTML?
you should know that official specifications may bear little resemblance to reality You
should always read any browser-specific documentation you can find to ensure that the
web browsers you're targeting support what you're attempting to accomplish Even then,
some experimentation will usually be required
The scripting lingua franca of today is JavaScript JavaScript was the first scripting language to be
implemented in a web browser, and currently enjoys the most widespread support across different web browsers Although you can create DHTML using other scripting languages such as VBScript, I
recommend always using JavaScript unless you are in a Microsoft-only environment (such as an
intranet)
As you'll see when we get to the DHTML examples, a large part of DHTML involves creating scripts that manipulate elements on a page You'll probably need to fall back on the discussion of JavaScript back in
Lessons 12, "Introducing JavaScript," and 13, "Using JavaScript in Your Pages," to refresh your memory
of JavaScript at times Because DHTML is really just an application of JavaScript, it might even be
helpful to think about this lesson as a follow-up to those
Two final notes about what DHTML actually is: DHTML (the scripting part of it) relies on something called
a Document Object Model (DOM) to identify, create, and manipulate elements on a web page For
example, you have to be able to identify an element, such as an image, in order to manipulate it with a script Likewise, you must be able to identify an element's style in order to change it This is what the DOM does It provides a bridge between the content of the web page and scripts
Finally, DHTML relies on event handling to track the actions of the web browser and user When the
page loads, the onload event is triggered Likewise, when a visitor clicks a button in a form, several
events might be triggered that you, the DHTML author, can use to run scripts Event handling is covered
in more depth later on
Trang 4Using the Document Object Model
Using the Document Object Model
When you think of a web page, you probably think of the document that's produced when it's displayed
in the browser, or the HTML codes that you see when you use your browser's View Source functionality However, there are other ways that the same data can be represented Modern web browsers create a representation of a page that can be accessed via scripts in a standardized fashion This representation
is called the Document Object Model, or DOM Under the DOM, the page content is treated as a tree of
objects I'm using the word objects the way a software developer would In that parlance, an object is a component that generally has different properties, methods, and event handlers A property is data that somehow describes the object A method is a function you can call to make the object do something or
to manipulate the object itself An event handler is a hook you can use to enable the object to respond
to an action (generally an action performed by the user) If you were speaking grammatically, you'd say that properties are an object's nouns and methods are its verbs
Note
Fully realizing the capabilities of the DOM requires a depth of knowledge beyond the scope
of this book But, as with other webrelated code, you can learn a lot by cutting and pasting
scripts and taking the time to study their results
DOM Data Types
When a DOM representation of a web page is created, all of the objects that are used to construct the
page are assigned to various categories, which are called interfaces in the world of object-oriented
programming If an object has a certain interface then it has the properties and methods associated with that interface For example, all of the tags on a page have the element interface, which means that they support methods such as getAttribute and setAttribute The generic data types that make up the DOM are listed in Table 15.1
Table 15.1 Interfaces in the DOM
Data Type Purpose
document This is the root object in the DOM
node All of the other interfaces mentioned are children of the node interface, and express all
of its properties and methods
element All the tags on a page express the element interface, and thus inherit all its properties,
methods, and event handlers
nodeList An array (or list) of elements Some method calls return lists of elements For example,
you can fetch all the items in a list or all the children of any element The results are returned in a nodeList
attribute Attributes of tags have their own interface
NamedNodeMap An alternative form of list for dealing with groups of elements
Trang 5Using the Document Object Model
Objects in the DOM
The base of the DOM tree is the document object The document object should look familiar to you from the examples in Lesson 13 You can call methods of the document object directly, such as document.write () to add content to the page, or you can reference children of the document object, using methods such as getElementById() or getElementsByTagName()
Even if you don't explicitly use the document object, you're still accessing the DOM any time you
reference objects on the page For example, in the form validation example in Lesson 13, I passed the form object to the validation function using the onsubmit handler and this In that case, this referred to the form being validated Had the form not been passed to the function using an argument, it could have been referenced by name or count using the document object
Another object that you'll deal with frequently is window The window object (unlike document) is not
formally part of the DOM, but browsers include it in order to provide an interface to the browser itself For example, the height and width of the browser window are properties of the window object rather than the document object
Each element on the page is also an object unto itself and is accessible using the document object Using generic methods, you can get to all the children of the document object, but a number of convenience methods are included to give you shortcuts to things such as the forms, images, and links on a page Before going further, let's look at an example
There's More to the DOM
The DOM consists of many more objects as well, but discussing each of them in detail is
beyond the scope of this lesson There are up-to-date online DOM references provided by
the browser vendors online Microsoft's DOM/DHTML reference is at http://msdn.microsoft
com/workshop/author/dhtml/_dhtml_node_entry.asp
The DOM reference for Netscape and Mozilla is at http://www.mozilla.org/docs/dom/
domref/
Opera attempts to hew as closely to published standards as possible Notes on their
departures from the specification can be found at http://www.opera.com/docs/specs/
Using the DOM
You should be thankful that I'm not going to discuss the DOM in detail because it would be incredibly dry and boring, and chances are whatever I put in this book would be at least somewhat out of date not a year after it is published For reference materials on the specific properties, methods, and event
handlers for each object in the DOM, you should rely on the vendor references Generally speaking, web programmers use the DOM in a few specific ways I'll go over those
Trang 6Using the Document Object Model
In this example, we're going to create a web page that enables us to manipulate elements on a page in various ways using the DOM This example will work in any modern browser that supports the DOM First, let's get the code listing out of the way:
Input
<html>
<head>
<title>DOM Example</title>
<script language="JavaScript">
function changeBgColor(newColor)
{
if (document.body)
{
eval('document.body.bgColor="' + newColor + '"');
}
}
function tackOn(headingText)
{
if (document.body)
{
if (headingText)
{
var newHeading = document.createElement("h1");
someText = document.createTextNode(headingText);
newHeading.appendChild(someText);
document.body.appendChild(newHeading);
}
}
}
function setHeadingColors()
{
var headings = document.getElementsByTagName("h1");
for (var i = 0; i < headings.length; i++)
{
headings.item(i).style.color = "yellow";
}
}
</script>
</head>
<body>
<form>
Background color:
<select onchange="changeBgColor(this.options[this.selectedIndex].value);">
<option value="white">white</option>
<option value="red">red</option>
<option value="blue">blue</option>
</select><br />
Add heading:
<input type="text" value="Spam" id="newHeading" />
<input type="button" value="tack it on"
onclick="tackOn(document.getElementById('newHeading').value);" />
Trang 7Using the Document Object Model
<br />
<input type="button" value="change colors"
onclick="setHeadingColors();" />
</form>
</body>
</html>
Let me describe quickly how the page works The form on the page enables you to change the page's background color, add new headings to the page, and set the color of all the headings currently on the page to yellow We accomplish this using three JavaScript functions and five form fields A screenshot of the page after I've manipulated it a bit appears in Figure 15.1
Output
Figure 15.1 A page that demonstrates how the DOM is used.
I use the DOM in both the event handlers called within the form as well as within the actual JavaScript
on the page The first form field is the select list that's used to change the page's background color To accomplish this, we use the onchange handler for this field When the value of the field is changed, the
changeBgColor() function defined on the page is called, and the new background color is passed in as a parameter We obtain this value by retrieving the value of the currently selected option using this
reference:
this.options[this.selectedIndex].value
this refers to the select field The options method retrieves a nodeList of options associated with the field We can obtain the currently selected index of the field using the selectedIndex property of the
Trang 8Using the Document Object Model
select list, and use it as the index for the nodeList Based on the DOM specification, I know that we could just as easily obtain the currently selected index using options.item(this.selectedIndex) Both approaches are valid Finally, the value property of the currently selected option is what's actually
passed in to the function
Now let's look at the changeBgColor() function This function is quite short First, it performs a simple test to verify that the document.body property even exists If the function can't get a reference to the body element in this way, there's no sense in going on Once it has it, it uses the eval function to create and run a bit of JavaScript that sets the bgColor property of the body element to the value that was passed in bgColor is a property that's specific to the document body; it's not available for all elements
Next, I enable the user to add <h1> elements to the page This bit of manipulation is accomplished using only methods and properties that are part of the core DOM, except for document.body This is intended to demonstrate how elements on a page can be treated in a generic fashion This part of the form uses two form fields; the first is a text field that provides the value of the text to be added The second part is a button that calls the function that appends the new heading to the page The only notable thing about the text field is that we've assigned it an ID, "newHeading"
The button uses an onclick handler to call the tackOn() function As its parameter, it passes in the value
of newHeading As you can see, it references newHeading using the getElementById method of the document
object, and then referencing the value property of that element I included a default value in the form field so that the user doesn't have to type in something every time
As you saw back in Lesson 9, "Creating Layouts with CSS," the id attribute can be used to assign an identifier to an element so that you can apply styles to it individually As you can see from this example, you can also access items with an id through the DOM using the getElementById() function This one capability alone makes the entire DOM worthwhilebefore the getElementById() function was supported
by browsers, referencing a specific object on a page was tedious and difficult Now all you have to do is assign an identifier to it The only catch is that you have to make sure not to use the same identifier more than once on the same page
Now let's look at the tackOn() function Before we do anything else, we make sure that document.body is supported and that a value was actually passed in There's no need to go further if we're not able to add
on the heading or there's no heading to add Once we've done that, we use the document.createElement () method to create a reference to a brand new <h1> element Then we use document.createTextNode()
to create a text node containing the header text To associate the text node with the heading, we use
appendChild() to indicate that the new text node is a child of the heading This is how you build onto your document structure using the DOM You generate new elements, and then add them onto existing elements as children We could also modify any properties of the heading that we wanted at this point
Once we have a reference to an <h1> element with some text as its child, we use appendChild() again to append the new heading onto the document body At this point, the new heading should appear at the bottom of the page When thinking of parent-child relationships in the DOM, just remember that, in HTML, if one object is a child of another, it just means that it's inside it For example, take a look at this HTML:
<p>The quick brown fox <em>jumped over</em> the lazy dog.</p>
The quick brown fox is a child of the paragraph tag So is the <em> tag The text jumped over is a child of the <em> tag, and the lazy dog is the third child of the <p> tag That's how the DOM tree works To
construct this text using JavaScript, you could use the following code:
Trang 9Using the Document Object Model
var newParagraph = document.createElement("p");
someText = document.createTextNode("The quick brown fox ");
newParagraph.appendChild(someText);
var newElement = document.createElement("em");
someText = document.createTextNode("jumped over");
newElement.appendChild(someText);
newParagraph.appendChild(newElement);
someText = document.createTextNode(" the lazy dog.");
newParagraph.appendChild(someText);
document.body.appendChild(newParagraph);
Yes, it really is easier to just write the HTML In any case, let's move on to the next part of the example The last method of modifying the page is with a button labeled Change Colors It uses the onclick
handler to call the setHeadingColors() function This function uses the document.getElementsByTagName()
to retrieve all instances of the <h1> tag on the page We then use a loop to iterate over the individual elements (which are stored in a nodeList), and set their color to yellow It's worth looking at this a bit more closely
This example demonstrated how to modify the style sheet for a page from JavaScript using the DOM The style property provides access to all the properties associated with the element it is associated
with In this case, we use style.color to change the color to yellow By the same token, we could use
style.backgroundColor to change the background color When you transform property names in CSS to attributes in the DOM, the hyphens are removed and the words that follow hyphens are capitalized
Trang 10Coping with Reality: Cross-Browser DHTML Techniques
Coping with Reality: Cross-Browser DHTML Techniques
The majority of the day thus far has been devoted to understanding the technologies behind DHTML and how to use them separately It's time to start creating real DHTML web pages As I've mentioned, the real challenge is creating DHTML so that you reach the largest possible audience within certain practical
limitations I say practical because true DHTML isn't possible in any web browser that doesn't implement
scripting or style sheets, and impractical in those that suffer from partial or poor implementations In other words, using DHTML, you'll never be able to reach 100% of your potential audience
There are a number of different approaches you can take when creating Dynamic HTML, given that not all browsers are created equal when it comes to support for JavaScript and cascading style sheets The first option is to create separate pages for separate browsers, or separate style sheets and JavaScript files for separate browsers This requires a lot of duplicated effort, and can be extremely painful
The second option is to try to write your code so that it will work with as many browsers as possible, no matter how poor their support for standards is This is often what happens when Netscape Navigator 4 is
in the mix, or even older versions of Internet Explorer The version 4 generation of browsers was the furthest from standards compliance browsers have ever been It was common for pages to include
massive amounts of extra code that figured out which browser was viewing the page and accounting for how its DHTML model works This technique is still relatively common, but I'm not going to cover it
today
The third option is to create your pages so that they work in browsers that implement the current web standards, and degrade gracefully in older browsers Given the small percentage of users who still use older browsers, unless you're specifically required to support them, just making sure that your pages aren't broken in them should be enough
Sniffing for Browsers
At one time, the most common technique for creating cross-browser DHTML was detecting the user's
web browser (commonly called sniffing) After you determined which browser the user was using, you
could simply execute the code tailored to that browser
The problem is that there are many browsers out on the market, and many versions of each one For example, there are two or three versions of both Netscape and Internet Explorer in fairly common usage even today As you might imagine, accounting for all the available browsers and keeping your scripts up-to-date to accommodate new browsers is a daunting task
Here's a relatively simple browser sniffer that detects only Netscape Navigator 4 and Microsoft Internet Explorer 4 and up It doesn't distinguish between Netscape 7 and Netscape 4, which are completely different, and doesn't even take browsers like Opera (or other common browsers) into consideration You may run into code like the sample that follows, but you shouldn't use such code yourself The
following listing creates variables that parse the appropriate objects to return true or false values for the final variables: is_nav4up and is_ie4up
// Trimmed down browser sniffer that
// detects Navigator 4+ and IE 4+
// Reference is_nav4up and is_ie4up in other
// portions of the script
var agt = navigator.userAgent.toLowerCase();