Chapter 5
JavaScript and the web go together like cheese and pizza: You could have one without the other, but why?
JavaScript gives web pages the ability to change dynamically in response to user input. To get the most out of the integration between JavaScript and the web, you need to know a little bit about how web pages are built.
In this chapter, we explore the language of the web, HTML, and we show you how to use JavaScript to work with and change the HTML inside of web pages.
HTML stands for Hypertext Markup Language. That’s a fancy way of saying that HTML is a language that’s used to create links (hypertext). HTML is so much more than simply a language for creating links, though.
HTML forms the skeleton that the text, pictures, and JavaScript in web pages attaches to.
Markup languages, such as HTML, were invented in order to give documents (such as letters, books, or essays) structure that a computer can understand and do things with.
Listing 5-1 shows a simple list that a person can understand with no problem.
Listing 5-1 A List
Things I Need
carrots
celery
spinach
As a person, you see this list and immediately understand it. But to a computer, this list has some issues. For example, a computer has no way of knowing that Things I Need is a title rather than an item on the list. Figure 5-1 is what it looks like when you view Listing 5-1 with a web browser.
To make this text document understandable to a web browser, we need to use HTML to “mark it up.”
HTML is made up of tags. The tags on clothes give you information about what the clothes are made of and how to wash them. Similarly, tags in HTML give you information about the content of a web page.
Tags are made up of keywords inside of angle brackets (< and >) and then come in two basic types: the beginning tag and the ending tag. Here’s an example of a beginning tag:
<p>
The p tag, is how you mark up text in a document as a paragraph.
Most beginning tags also have matching ending tags. The only difference between a beginning tag and an ending tag is that an ending tag has a / before the name of the tag. For example, here’s the ending p tag:
</p>
To use tags, just put the thing that you want to mark up (such as text, images, or even other tags) between the beginning and ending tags. For example, here’s how you would mark up a paragraph of text in HTML.
<p>This is a paragraph of text. A paragraph has space
before and after it in order to separate it from the
other paragraphs of text in a document.</p>
When you have a beginning tag, an ending tag, and content between them, we call the whole thing an HTML element.
HTML has a bunch of tags that you can use to label different parts of a document. Examples of tags include <p> for paragraph, <img> for image, <audio> for audio clips, <video> for video clips, <header> for the top of a web page, and <footer> for the bottom of a web page.
Listing 5-2 shows the list from Listing 5-1 marked up as an HTML document, made up of tags and text.
Listing 5-2 A Simple HTML Document
<html>
<head>
<title>My Grocery List</title>
</head>
<body>
<h1>Things I Need</h1>
<ol>
<li>carrots</li>
<li>celery</li>
<li>spinach</li>
</ol>
</body>
</html>
Figure 5-2 shows what the web page in Listing 5-2 looks like when you view it with a web browser. That’s much better, right?
Notice that HTML tags don’t actually appear in the web browser. Instead, they modify how the web browser displays text, images, and more.
Creating web pages is pretty easy once you know a few things about how they’re built. The first thing to know is that most web pages share a very similar basic structure, and they all must abide by just a few basic rules.
The first rule of creating HTML documents is that tags need to be opened and closed in the right order. One way to remember the order in which tags are opened and closed is FILO, which stands for First In, Last Out.
Notice that the web page in Listing 5-2 starts with the <html> tag and ends with the </html> tag. This is how every web page should start and end. All the other tags in a web page are “inside” the html tags, and they’re closed according to FILO.
For example, the <head> element is inside of <html>. Therefore, the closing head tag must come before the closing html tag. The <ol> tag (which stands for ordered list) comes after the <body> tag, so <ol> is inside of <body> and the </ol> tag must come before the </body> tag.
Another rule of creating HTML documents is that web pages always have a head element and a body element.
The head element: The head element is like the brain of your web pages. JavaScript code often goes into the head element, but it doesn’t display in the web browser window.
In Listing 5-2, we have only a title element in the head. The title is what displays at the top of the browser window or in your browser’s tab when you’re on a web page. The contents of the title element are also typically what shows up as a link in search results.
The body element: The body element is where everything that you want to display in the web browser goes.
In Listing 5-2, we have several elements in the body. Let’s take a look at each of these:
Follow these steps to make your own list in JSFiddle.
http://jsfiddle.net
.Drag and drop the pane borders to make the HTML pane in JSFiddle as large as you like.
We’re only going to be working with the HTML pane for now, so make sure you’re comfortable and have plenty of space.
Type the following basic HTML template into the HTML pane.
<html>
<head>
<title>HTML Template</title>
</head>
<body>
<h1>A basic HTML template</h1>
</body>
</html>
As soon as you type <html>, you get a warning message from JSFiddle, as shown in Figure 5-3, telling you that <html> is already included in the output. What’s going on here is that the basic HTML template is so basic that JSFiddle will just help you out by putting it in there for you. Thanks, JSFiddle!
Because the basic template is already there, go ahead and delete everything from the HTML window except for what’s between <body> and </body> (the h1 element).
Always keep in mind that the <html>, <head>, and <body> elements should be part of every web page, even if you don’t need to type them yourself when you’re working in JSFiddle.
Click Run.
The text between the <h1> and </h1> tags will display in the Output pane, formatted as a first-level heading, as shown in Figure 5-4.
HTML has quite a few elements. Because this is a JavaScript book, we don’t have room to talk about each of the elements here. But we’ll cover just enough of them to allow you to build some awesome web pages. For the rest, you can go online to read more.
Table 5-2 lists the most commonly used HTML elements, along with descriptions of what they’re for.
Table 5-2 The Most Common HTML Elements
Element |
Name |
Description |
<h1> through <h6> |
Headings (levels 1 through 6) |
A section heading. |
<p> |
Paragraph |
A paragraph. |
<em> |
Emphasis |
Adds emphasis to a word or words. Typically displayed as italics in web browsers. |
<strong> |
Strong |
Represents strong importance. Typically displayed as bold text in web browsers. |
<a> |
Anchor |
A link. |
<ul> |
Unordered list |
A bulleted list. |
<ol> |
Ordered list |
A numbered list. |
<li> |
List item |
An item within an ordered or unordered list. |
<img> |
Image |
An image. |
<hr> |
Horizontal rule |
A horizontal line on the page. |
<div> |
Division |
A way to separate a document into different parts. |
Let’s have some fun with your new elements. We’re going to write a fun web page all about you!
Go back to JSFiddle and follow these steps:
Delete everything from the HTML pane and click Run.
The Output pane should now be blank.
Add a p element and type a favorite quote, a sentence about yourself, or the following text between the start and end tags:
I'm learning to build dynamic web pages with JavaScript and HTML!
Click Run.
If you’re following along closely, your code should look something like this:
<h1>Eva</h1>
<hr>
<p><em> I'm learning to build dynamic web pages with JavaScript and HTML!</em></p>
The output should now look something like Figure 5-5 (but with your own information, of course!).
Create a new paragraph and put the following text into it:
Here are some of the things I like to do:
<ul>
<li></li>
<li></li>
<li></li>
</ul>
Put something that you like to do into each of the list item elements.
Listing 5-3 shows what our sample code looks like now.
Listing 5-3 The Updated Home Page
<h1>Eva</h1>
<hr>
<p><em>I'm learning to build dynamic web pages with JavaScript and HTML!</em></p>
<hr>
<h2>Things I Like</h2>
<p>Here are some of the things I like to do:</p>
<ul>
<li>Write</li>
<li>Dance</li>
<li>Travel</li>
</ul>
Click Run to preview your web page in the output pane. It should now look like Figure 5-6.
HTML elements are pretty powerful just by themselves, and they can make web browsers do some pretty fancy things with your content. However, HTML has another trick up its sleeve that makes HTML even better: HTML attributes!
HTML attributes are a way to give web browsers more information about elements. Attributes are added to elements using what’s called a name/value pair. For example, the img element uses attributes to tell what image should be displayed, and what should be displayed instead of the image if the file isn’t found:
<img src="picture.jpg" alt="Here's a picture of me">
In this example, src and alt are attributes.
Each element in HTML has a list of attributes that can be added to it. Some attributes, such as src and alt, change the way an element behaves or what it does. Other attributes, such as the id attribute, just provide the browser with more information about the element.
The id attribute uniquely identifies a single element in your document. You may have any number of li elements, for example, but if you give each li element an id attribute, you can tell them all apart … and so can JavaScript!
We’ll be making use of the id attribute quite a bit in upcoming programs.
Let’s add some id attributes to the HTML in your home page now.
Add an id attribute to the h1 to identify it as containing your name.
<h1 id="myName">
Find the p element between the two hr elements, and modify the starting tag to add an id of aboutMe, like this:
<p id="aboutMe">
Add a unique id attribute to each of the list items, like this:
<li id="firstThing"></li>
<li id="secondThing"></li>
<li id="thirdThing"></li>
When you’re finished adding id attributes, your web page should look something like Listing 5-4.
Listing 5-4 The Updated Home Page with id Attributes Added
<h1 id="myName">Eva</h1>
<hr>
<p id="aboutMe"><em>I'm learning to build dynamic web pages with JavaScript and HTML!</em></p>
<hr>
<h2>Things I Like</h2>
<p>Here are some of the things I like to do:</p>
<ul>
<li id="firstThing">Write</li>
<li id="secondThing">Dance</li>
<li id="thirdThing">Travel</li>
</ul>
Click Run to preview the web page in JSFiddle. You should notice … nothing. The page looks exactly the same with the id attributes as it does without them. Yes, we know, it’s not that exciting. But wait until you see what JavaScript can do with id attributes!
By using JavaScript, you can change any part of an HTML document in response to input from the person browsing the page. We show you exactly how to do that in this section.
But before we get started, let’s take a look at a couple concepts that we use in this section. The first is a method called getElementById.
getElementById is probably the easiest and most commonly used way for JavaScript programmers to work directly with HTML. Its purpose is to locate an individual element in a document so that you can change it, delete it, or add something to it.
Another word for locating an element is selecting an element.
To use getElementById, first make sure that the element you want to select has an id attribute. Then just use the following formula to locate that element:
document.getElementById("id-value")
For example, to select an element with an id value of myName, you can use this code:
document.getElementById("myName")
When you have an element, the next logical thing to do is to make a change to it.
innerHTML is a property of every element. It tells you what’s between the starting and ending tags of the element, and it also lets you set the contents of the element.
For example, let’s say you have an element like the following:
<p id="myParagraph">This is <em>my</em> paragraph.</p>
You can select the paragraph and then change the value of its innerHTML with the following command:
document.getElementById("myParagraph").innerHTML = "This is <em>your</em> paragraph!";
Now that you know a little about getElementById and innerHTML, let’s take a look again at our HTML home page.
You’ll add a button and JavaScript code to your home page to let you change your list of favorite things with the click of a button.
Add a button below the list with the following HTML:
<button id="changeList" type="button">
Change Your List
</button>
The button element causes the browser to create a button in your browser window with the label of the button set to the text between the starting and ending tags.
Create three new variables in the JavaScript pane.
var item1;
var item2;
var item3;
These three variables will be used to hold the values input by the user before they get written to the web page.
Make JavaScript pay attention to clicks on the button by adding this to the JavaScript pane in JSFiddle:
document.getElementById("changeList").onclick = newList;
We use a method called getElementById to locate the element in the document that has an id attribute set to changeList. As you know, this is the id value of the button.
When JavaScript has found the button, we use the onclick event handler to tell it to watch for clicks on that button. An event handler is exactly what it sounds like. It tells JavaScript how to handle different types of events that happen in the browser. In this case, mouse clicks.
If the event handler detects a click on the button, we tell it to run the function that we’ve called newList. A function is like a program within a program. We talk much more about functions in Chapter 12. For now, all you need to know is that functions don’t run until you tell them to by “calling” them.
Type these lines to ask the user for new list items:
function newList(){
item1 = prompt("Enter a new first thing: ");
item2 = prompt("Enter a new second thing: ");
item3 = prompt("Enter a new third thing: ");
updateList();
}
The first line of this block of code is what makes it a function. It tells JavaScript not to run the code between { and } until the function is called (using its name, newList).
Inside the function, we gather three new list items from the user, using the prompt command.
Finally, we tell JavaScript to run the function called updateList, which we’ll write in the next step.
Tell JavaScript to update the three list items.
function updateList() {
document.getElementById("firstThing").innerHTML = item1;
document.getElementById("secondThing").innerHTML = item2;
document.getElementById("thirdThing").innerHTML = item3;
}
The updateList function finds each of the list items using their id attribute values. It then uses a method called innerHTML to change the value that’s between the starting and ending tags of the list item to the values that the user entered into the prompt.
After the updateList function gets run, the values of the three list items should change to the new values entered by the user.
When you’re finished, your code in the JavaScript pane should match Listing 5-5. Check it very carefully before moving on to make sure you don’t have any syntax errors.
Listing 5-5 The Final JavaScript for the HTML Homepage App
var item1;
var item2;
var item3;
document.getElementById("changeList").onclick = newList;
function newList() {
item1 = prompt("Enter a new first thing: ");
item2 = prompt("Enter a new second thing: ");
item3 = prompt("Enter a new third thing: ");
updateList();
}
function updateList() {
document.getElementById("firstThing").innerHTML = item1;
document.getElementById("secondThing").innerHTML = item2;
document.getElementById("thirdThing").innerHTML = item3;
}
If you did everything correctly, you should now be able to click the button, enter new text into each of the three prompt windows, and then see the new items instead of the three original list items, as shown in Figure 5-7.