HTML and CSS Reference
In-Depth Information
<head>
<title>JavaScript Practice</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Using JavaScript</h1>
<h2>Hello
<script type="text/javascript">
<!-- <![CDATA[
var userName;
userName = "Karen";
document.write(userName);
// ]]> -->
</script>
</h2>
</body>
</html>
Notice that the <h2> tag is placed before the script block and the </h2> tag is placed
after the script block. This renders the userName in the <h2> heading format. There is
also a single space after the “o” in “Hello”. If you miss this space, you'll see the
userName value displayed right after the “o”.
Notice that the variable is mixed case. This is a convention used in many programming
languages to make the variable readable. Some developers might use an underscore, like
user_name. Selecting a variable name is somewhat of an art form, but try to select
names that indicate the contents of the variable.
Notice also, that the document.write() method does not contain quotes. The contents
of the variable will be written to the document. If we had used quotes around the vari-
able name, the variable name itself would be written to the document, and not the con-
tents of the variable.
Save this document as variablewrite.html and load it in the browser. Figure 14.13
shows the variablewrite.html file in the browser.
Figure 14.13
Browser with
variablewrite.html
displayed
Chopping up the <h2> heading so that it is placed before and after the script is a bit
cumbersome. We can combine strings using the plus (+) symbol. You'll see later in this
chapter that the plus symbol can also be used to add numbers. Combining strings using
the plus (+) symbol is called concatentation . Let's concatenate the <h2> information as a
string with the username value and the </h2> tag.
 
Search WWH ::




Custom Search