CSS, HTML and Javascript
Audience and Pre-Requisites
This tutorial covers just what you need to know about CSS, DHTML and JavaScript in order to work with AJAX. The pre-requisites are knowledge of HTML, basic CSS and programming experience with a language such as C++, Java or a scripting language like Javascript, Python or PHP.
If you need to review your HTML, there are many excellent web-based tutorials. For CSS, here is a good introductory tutorial, and reference materials.
A Simple Example
Introduction
A few years ago, most web content was static, that is, we put HTML elements (paragraphs, images, links) in a specific order in our HTML file, and the browser always showed the elements in that order. If we wanted to change the order, we had to rewrite the HTML, or we could use some server-side techniques. Today, there are many different techniques available to bring web pages alive, making them more dynamic and interactive.
DHTML or Dynamic HTML is one such technique. It gives us the opportunity to re-organize our pages dynamically, on the client-side. For example, we can take an element (say, an image or text) out of its defined order on the page and put it somewhere else. Then we can change its position again if the user clicks on a link or a button. We can change colors, font, style, animate, do just about anything to the basic elements of the HTML.
Click here to see an example.
How did we do this? Well, we use CSS to define the presentation, or style definitions of a web page as well as the location of elements. Then, we use Javascript to change those definitions. In other words, DHTML = CSS + JavaScript and with this, we can re-organize our pages on the fly.
Document Object Model
A key component of DHTML is the Document Object Model (DOM). DOM is a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure and style of documents. This model describes each web page element, which of its properties can be changed, and how to do it. DOM provides an object-oriented programming interface between HTML/CSS and JavaScript. There is a lot to know about DOM, but we are going to focus on just what you need to learn AJAX.
DOM represents a document as a tree. Every node of the tree represents an HTML tag, or a textual entry inside an HTML tag. The tree structure accurately describes the whole HTML document, including relationships between tags and textual entries on the page. A relationship may be of the type child, parent, or sibling. DOM allows you to navigate along the document tree, up and down, and to the sides. You can use the child, parent, and sibling relationships to go anywhere on your page tree, making changes as you go.
If you think of the HTML tag at the top of an HTML document as the root node of your document tree, then the structure of the tree becomes clear. Consider, for example, the following HTML document:
<HTML> <HEAD> <TITLE> Tiny Table </TITLE> </HEAD> <BODY> <TABLE> <TBODY> <TR> <TD>cell1</TD> <TD>cell2</TD> </TR> </TBODY> </TABLE> </BODY> </HTML>
Let's add a short Javascript function to the top of this file and run it onLoad():
function showNodes() { // get the rootElement of the document (HTML tag) var rootElement = document.documentElement; // get the rootElement's children (HEAD and BODY tags) var docNodes = rootElement.childNodes; // show the nodeName for the children for (i = 0; i < docNodes.length; i++) { alert(docNodes[i].nodeName); } // get the table cells - this returns an array of all TD's var myTableCells = document.getElementsByTagName("td"); for (i = 0; i < myTableCells.length; i++) { alert(myTableCells[i].nodeName); } }
Click here to see the output and view the source. Notice that we can traverse down to any element in the HTML, or jump to it directly using getElementsByTagName(). We can also change the value of HTML elements. Click here to see how we create and add a new table cell using the following Javascript function:
function changeTDNodes() { // there can be many "tr" elements; just return the first/zeroth element var mycurrent_row = document.getElementsByTagName("tr")[0]; // create a new td cell mycurrent_cell = document.createElement("td"); // creates a text node currenttext = document.createTextNode("new cell3 here"); // appends the text node we created into the cell <td> mycurrent_cell.appendChild(currenttext); // appends the cell <td> into the row <tr> mycurrent_row.appendChild(mycurrent_cell); }
To work with DOM, you just need to know the properties and methods of the various objects. Click here for reference materials, and here for examples.
DOM, CSS and Javascript Together
Going back to our simple example, we use DOM to access and modify the style definition of a single HTML element, which is just a snippet of text. The first thing we do is use the "div" tag to give the snippet a name:
<DIV ID="myText">Change Me!</DIV>
We place it on the screen, and style it, in our CSS at the top of the file:
#myText {position: absolute; top: 100px; left: 400px; font: 24px arial; font-weight: 900; }
Here is the function for accessing the object and its style property:
// "myText" is passed in as the name function getObj(name) { if (document.getElementById) { this.obj = document.getElementById(name); this.style = document.getElementById(name).style; } else { return; } }
Finally, once we have the object representing our text snippet, we write a Javascript function to modify it:
function changeColor(color) { // call function to get the object var myObj = new getObj('myText'); // change its color to the incoming value myObj.style.color = color; }
More Examples
Here are some websites that have additional examples showing how to access various HTML elements through DOM, and manipulating them with Javascript.
-
Traversing an HTML Table with Javascript and DOM
-
Several short DHTML/DOM examples showing many different DOM objects
- Several Javascript/DHTML examples showing various Javascript techniques using DOM and CSS
Exercises
-
It's helpful to have a Javascript debugger available when doing AJAX programming. Venkman is available as a plug-in to Firefox, and provides all the basic capabilities of a graphical debugger. This first exercise will get you up and running with Venkman. We'll assume that you have installed the plug-in, and restarted Firefox. Start up the debugger from the Tools menu.
Click here to open an HTML file that contains some Javascript - it's best to open this in another Firefox window, so you can follow along here as well. This file brings up an HTML form for input with a Javascript function validating input once the Validate button is clicked. Bring up the debugger screen. You should see something like this:
You may need to click on one of your browser windows in the Open Windows area to find debug.html. Clicking on that file will bring up its HTML. In order to set breakpoints and trace the code in the debugger, you need to have the HTML file open in your browser. When this is the case, the code in the right window will have dashes in the left-most column of the window. This is where you can set breakpoints.Go ahead and set one, somewhere in the for-loop. Then return to the HTML form and press the Validate button with no data entered. It should bring up your debugger window with the breakpoint line highlighted.
An important feature allows you to modify local variables in an interactive session.. Depending on your browser version, you may have an interactive session present in the lower right window. If not, click on View -> Show/Hide -> Interactive Session. This should bring up another box in the left lower part of the debugger window. Click the little box in the upper left of the interactive window. A command line session should appear. Your screen may look something like this:
There is a little box at the bottom of the interactive session window where you can enter input. Try this:a = 2 (enter)
b = 3 (enter)
a + bVenkman has many other features, which you can explore by looking at some web-based resources.
-
Using the HTML file "Tiny Table" (shown below), find the text nodes in the document tree and replace them with their upper-case equivalent. Write a Javascript function that finds the text nodes, (hint: nodeType has a value of 3 for text nodes), and uses toUpperCase() to do the conversion. You may want to create a new node, upper-case the text, and then use the replaceChild() function to place your new node in the tree. Call your function using the onLoad() attribute of the BODY tag, so the upper-case text appears when the file is opened.
<HTML> <HEAD> <TITLE> Tiny Table </TITLE> </HEAD> <BODY> <TABLE> <TBODY> <TR> <TD>cell1</TD> <TD>cell2</TD> </TR> </TBODY> </TABLE> </BODY> </HTML>
-
Layers are an important aspect of DHTML documents. With layers, we can control sections of an HTML document. Here is how we can create layers:
<html> <head> <title>Layers</title> </head> <body> <div ID="layer1" STYLE="position: absolute; left: 280; top: 100; width:200; height:100; background-color:magenta"> <h2> Layer 1</h2> Layer 1: on right </div> <div ID="layer2" STYLE="position: absolute; left: 20; top: 100; width:200; height:100; background-color:cyan"> <h2> Layer 2</h2> Layer 1: on left </div> </body> </html>
Write a Javascript function that flips these two layers around on the screen. Then, enhance your program to allow a user to move any layer around the screen that they want. Use the following as a model:
- Figure out how to animate a text string, image or whatever you like using DHTML. You may want to check into the window.setTimeout() method.
This collection, CSS, HTML and Javascript , by Google Code University Based on a work at code.google.com. is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International license.