Adding Scripts

Another means of bringing interactivity and interest to your pages is adding scripts to them. Typically, this refers to JavaScript or what is known as Dynamic HTML or DHTML, which is a combination of technologies, including HTML, CSS, JavaScript, and the Document Object Model. Combining these technologies gives you rich features such as drop-down menus and interactive games.


The Document Object Model, also referred to as the DOM, is the interface within browsers that enables you to attach scripting to specific elements. Part of the reason DHTML has been controversial and problematic is that browsers have implemented nonstandard DOMs, which have resulted in poor consistency. When you are looking for DHTML scripts, be sure that you're using those scripts that offer the most cross-browser support. The DOM is standardized, and all contemporary, standards-based browsers are working to implement DOM standards efficiently.

You can add scripts to your document in two primary ways. One is to place the script into the head portion of your document. This is referred to as an embedded script. The other way is to place your script external to the document, which is referred to as a linked script.

Embedding a Script

To embed a JavaScript in the head portion of your document, you use the script element to contain the script (see Example 3-9).

Example 3-9. Embedding a script into the head of a document
           <script type="text/javascript">
           function newWindow() {foodWindow ="images/photo.jpg",
           "foodWin", "width=250,height=188")}

The purpose of this script is to set up the document to open the image photo.jpg in a new window when a specific link is clicked. You also need a bit of script in the actual link found in the body of the document, as follows:

<a href="javascript:newWindow()">Delicious Vietnamese Lunch</a>

Figure 3-12 demonstrates how clicking on the link makes the pop-up window appear with the image intact.

Figure 3-12. The results of the embedded script.

Linking to a Script

In terms of best practices, the more you can get out of your document and into external files in terms of scripting and style, the better. You can have many pages pointing to one script, and if you require changes to the script, you can make them to the one script file instead of to many documents with embedded scripts.

To link to the script, first place the script code (without any HTML) into a separate file, and name the file with a .js extension, as in popup.js. You can place that file into a subdirectory named scripts (just as you did with images and media), and then use the script element to link it to the document (see Example 3-10).

Example 3-10. Linking to the script
<script src="scripts/popup.js" type="text/javascript"></script>

Leave the link code as is within the body of the document, and the results will be exactly the same as demonstrated in Figure 3-12.

by BrainBellupdated