JavaScript and XHTML

The rules for using JavaScript in XHTML are a bit different from using JavaScript with HTML 4.01. Here is a sample document showing a JavaScript function integrated with HTML 4.01.

<html><head><title>A Basic Function</title>
<script type="text/javascript" language="JavaScript">
<!-- Hides scripts from really old browsers.
function doSomething(){
var theVisitor = document.myform.visitor.value;
window.alert("Is this OK, " + theVisitor + "?");
}
//Ends script hiding -->
</script>
</head>
<body bgcolor="white">
<p>Please type your name and click the button.</p>
<form name="myform">
<input type="text" size="30" name="visitor"><br>
<br>
<input type="button" name="mybutton" value="Do Something" onclick="
doSomething();">
</form>
</body>
</html>

Now here is the same page re-written to comply with the rules of XHTML.

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A Basic Function in XHTML</title>
<script type="text/javascript" language="JavaScript">
// <![CDATA[
function doSomething(){
var theVisitor = document.getElementById('visitor').value;
window.alert("Is this OK, " + theVisitor + "?");
}
// ]]>
</script>
</head>
<body>
<p>Please type your name and click the button.</p>
<form id="myform" action="">
<input type="text" size="30" id="visitor" />
<br />
<br />
<input type="button" id="mybutton" value="Do Something"
onclick="doSomething();" />
</form>
</body>
</html>

You may view the XHTML version in a new window by clicking here. Here are the key differences.

The script in the head section of the HTML 4.01 example is hidden from really old browsers using html comments. In XHTML you will likely wish to shield the contents of your script from the XML processor. The XML processor will expand all < and & characters into their equivalent character entities &lt; and &amp;. If that were to happen, many of your scripts would become non-functional. The same thing applies to the contents of the <style> </style> tag pair. To prevent this problem, wrap your script or style content with the CDATA marker as shown in the XHTML example.

<script type="text/javascript" language="JavaScript">
// <![CDATA[
...your script goes here
// ]]>
</script>

In practice, contemporary Web browsers such as Netscape 7 and Internet Explorer 6 will correctly interpret your scripts even if you use the old HTML 4.01 syntax but it is best to know the correct procedure. You can avoid the problem entirely by using external style sheets and external javascript files. The W3c recommends that as we move forward into the XML era, we should rely more on external style sheets and external scripts.