Web Development and Design Foundations with XHTML, 5th Edition

(Steven Felgate) #1

(^536) Chapter 14 A Brief Look at JavaScript
In this chapter we will touch on some of the highlights and concepts involved in using
JavaScript. We will create some scripts to demonstrate the use of the alert message,
mouseovers, and some of the techniques involved in checking a form for input errors.
This chapter offers just a taste of JavaScript, but it will give you a peek at how some of
the techniques are developed.


14.4Adding JavaScript to a Web Page


JavaScript code is embedded in an XHTML Web page and is interpreted by the Web
browser. This means that the Web browser is capable of understanding the code and
running it. The examples in this chapter use the Mozilla Firefox Web browser. The code
we will be creating will work in most Web browsers. However, we will use Firefox
because it will provide us with helpful error messages that will be invaluable when we
create and test our pages. If you have not already installed Mozilla Firefox on your
computer, visit http://www.mozilla.com/firefox for a free download.

The Script Element


When JavaScript code is embedded in an XHTML document, it needs to be contained,
or encapsulated, in <script>and</script>tags to identify it. Web pages are ren-
dered by the Web browser from top to bottom. The impact on our scripts is that they
will execute wherever they are located in the document, as we will see.
For XHTML conformance, the <script>tag must include an attribute to identify the
scripting language as "text/javascript".

JavaScript Statement Block Template


For XHTML Strict DTD conformance, the JavaScript statement block must include a char-
acter data declaration. When the W3C validator checks for XHTML Strict conformance, it
will check all the code on the page except for areas marked as character data sections.
Since JavaScript is not part of XHTML, many validation errors would be generated unless
the JavaScript is placed in an area marked as a character data section. This issue does not
apply to Web pages coded using Transitional XHTML. However, it doesn’t do any harm to
add the character data declaration if you are using Transitional XHTML, so let’s include it.
XHTMLcommentsare contained between <!--and-->markup symbols. These comment
areas are ignored by the browser. Comments can also be used in JavaScript. The // (double
slash) identifies a single comment line and the /*and*/symbols identify a comment block.

Figure 14.6
The original image
on the left, and the
swapped image on
the right, with the
mouse pointer
hovering on the
image

Free download pdf