Chapter 5
In This Chapter
Understanding what HTML, CSS, and JavaScript do
Learning to do common HTML and CSS tasks
Practicing advanced JavaScript commands
The web as I envision it, we have not seen it yet. The future is still so much bigger than the past.
—Tim Berners-Lee, inventor of HTML
Many people start learning to code by building basic websites using HTML, CSS, and JavaScript. These easy-to-learn programming languages are visual, so you can see the product of your hard work displayed on the page. In addition, these languages form the basic building blocks of all websites used on the Internet.
You start by building static web pages with content that does not change often or at all, such as the menu page on a restaurant website. As you gain experience, you’ll build more complex websites with dynamic content, which changes based on user preferences and inputs.
In this chapter, you learn the basics involved in using HTML, CSS, and JavaScript.
HTML, or HyperText Markup Language, tells the browser how to display text and images on a web page. Think about how you create a document with a word processor. Whether you use Microsoft Word, WordPad, Apple Pages, or another application, your word processor has a main window in which you type text, and a menu or a toolbar with multiple options to structure and style that text (see Figure 5-1). You can create headings, insert pictures, underline text, and much more. Similarly, you can use HTML to structure and style text and other elements that appear on a website.
Markup language documents, such as HTML documents, are just plain text files. Unlike documents that can be viewed only with the word processor used to create the document, you can view an HTML file using any web browser on any type of computer.
CSS, or Cascading Style Sheet, styles HTML elements with greater control than HTML. Take a look at Figure 5-2. On the left is a Facebook page as you’d see it in your browser. On the right is the same Facebook page without the CSS styling; all the images and text appear left-justified, borders and shading disappear, and the text has minimal formatting.
JavaScript creates and modifies web page elements, and interacts with the existing web page HTML and CSS. See Figure 5-3. When you visit a web page containing JavaScript, your browser downloads the JavaScript code and runs it client side (on your machine).
JavaScript has continued to evolve. In the last decade, its most important innovation has allowed developers to add content to web pages without requiring the user to reload the page. This technique, called AJAX (asynchronous JavaScript), might sound trivial, but it has led to the creation of cutting-edge browser experiences, such as Gmail (shown in Figure 5-4).
Here is an easy way to think about AJAX: Imagine you’re at a coffee shop and have just ordered a coffee after waiting in a long line. Before asynchronous JavaScript, you would have to wait patiently at the coffee bar until you received your coffee before doing anything else. With asynchronous JavaScript, you can read the newspaper, find a table, phone a friend, and do multiple other tasks until the barista calls your name, alerting you that your coffee is ready.
HTML is used on every page you browse on the Internet. The purpose of HTML is to create the basic page layout and put text and images on the web page.
In a word processor, you typically style text by highlighting it with your cursor, and then applying an effect, such as bold or italics. With HTML, instead of pointing and clicking, you use special text keywords called elements, which apply a special effect.
The browser recognizes an element and applies its effect if the following three conditions exist:
When all three conditions are met, the text between the opening and closing tags is styled with the tag’s defined effect.
For a better understanding of these three conditions, check out the following example code:
<h1>This is a big heading with all three conditions</h1>
h1 This is text without the < and > sign surrounding the tag /h1
<rockstar>This is text with a tag that has no meaning to the browser</rockstar>
This is regular text
You can see how a browser would display this code in Figure 5-5.
The browser applies a header effect to “This is a big heading with all three conditions” because h1 is a header tag and all three conditions for a valid HTML tag exist:
The remaining lines of code are displayed as plain text because they do not fulfill all three conditions. On the second line of code, the <h1> tag is missing the left and right brackets, which violates the second condition. The third line of code violates the first condition because rockstar is not a recognized HTML element. (After you finish this chapter, however, you may feel like a rock star!) Finally, the fourth line of code is displayed as plain text because it has no opening tag preceding the text and no closing tag following the text, which violates the third condition.
Your browser can interpret over a hundred HTML tags, but most websites use just a few tags to do most of the work. To understand this, let’s try a little exercise: Think of your favorite news website. Have one in mind? Now connect to the Internet, open your browser, and type the address of that website. Bring this book with you, and take your time — I can wait!
In the event you can’t access the Internet right now, take a look at the article from my favorite news website, The New York Times, in Figure 5-6.
Look closely at the news website on your screen (or look at mine). Four HTML elements are used to create the majority of the page:
In the following sections I explain how to write code to create these common HTML features.
Use headlines to describe a section of your page. HTML has six levels of headings:
The browser renders h1 headings with a font size larger than h2, which in turn is larger than h3. Headings start with an opening heading tag, the heading text, and then the closing heading tag, as follows:
<h1>Heading text here</h1>
Here are some code examples showing various headings:
<h1>Heading 1: ”I’m going to make him an offer he can’t refuse”</h1>
<h2>Heading 2: ”Houston, we have a problem”</h2>
<h3>Heading 3: ”May the Force be with you”</h3>
<h4>Heading 4: ”You talking to me?”</h4>
<h5>Heading 5: ”I’ll be back”</h5>
<h6>Heading 6: ”My precious”</h6>
The result of these examples is shown in Figure 5-7.
To display text in paragraphs, you can use the p element. Place an opening <p> tag before the paragraph and a closing tag after it. The p element takes text and inserts a line break after the closing tag.
Paragraphs start with an opening paragraph tag, the paragraph text, and then the closing paragraph tag:
<p>Paragraph text here</p>
Following are examples of coding a paragraph.
<p>Armstrong: Okay. I’m going to step off the LM now.</p>
<p>Armstrong: That’s one small step for man; one giant leap for mankind.</p>
<p>Armstrong: Yes, the surface is fine and powdery. I can kick it up loosely with my toe. It does adhere in fine layers, like powdered charcoal, to the sole and sides of my boots.</p>
The result is shown in Figure 5-8.
Hyperlinks are one of HTML’s most valuable features. Web pages that include hyperlinked references to other sources allow the reader to access those sources with just a click, a big advantage over printed pages.
A hyperlink has two parts:
To create a hyperlink in HTML, start with an opening anchor tag (<a>) with an href attribute. Attributes modify HTML elements and are placed inside the opening HTML tag. Then add the value of the href attribute, which is the link destination. Then add text to describe the link after the opening anchor tag, and finally include a closing anchor tag.
The resulting HTML should look something like this:
<a href=”website url”>Link description</a>
Three examples of coding a hyperlink follow:
<a href=”http://www.amazon.com”>Purchase anything</a>
<a href=”http://www.airbnb.com”>Rent a place to stay from a local host</a>
<a href=”http://www.techcrunch.com”>Tech industry blog</a>
The resulting links are shown in Figure 5-9.
When rendering a hyperlink, the browser underlines the link and colors it blue by default.
Images spruce up plain HTML text pages. To include an image on your web page — your own or someone else’s — you must obtain the image’s web address. Websites such as Google Images (images.google.com
) and Flickr (www.flickr.com
) allow you to search for online images based on keywords. When you find an image you like, right-click the image and select Copy Image URL.
To include an image, start with an opening image tag <img>, define the source of the image using the src attribute, and include a forward slash at the end of the opening tag to close the tag. For example:
<img src=”http://upload.wikimedia.org/wikipedia/commons/5/55/Grace_Hopper.jpg”/>
<img src=”http://upload.wikimedia.org/wikipedia/commons/b/bd/Dts_news_bill_gates_wikipedia.JPG”/>
Figure 5-10 shows the result, with US Navy Rear Admiral Grace Hopper on the left and Bill Gates on the right.
CSS can style almost any HTML tag that creates a visible element on the page, including all the HTML tags you just saw to create headings, paragraphs, links, and images. With CSS, you can style the following:
CSS modifies HTML elements with rules that apply to each element. These rules are written as follows:
selector {
property: value;
}
A CSS rule is comprised of three parts:
The selector identifies which HTML element you want to style. In HTML, an element is surrounded by angle brackets, but in CSS the selector stands alone. The selector is followed by a space, an opening left curly bracket ({), the property with a value, and then a closing right curly bracket (}).
A line break after the opening left curly bracket and before the closing right curly bracket is not required by CSS. In fact, you could put all your code on one line with no line breaks or spaces. Developers follow the convention of using line breaks to make CSS easier to modify and read.
The following code shows you an example of CSS modifying a specific HTML element. The CSS code appears first, followed by the HTML code that it modifies. First, the CSS:
h1 {
font-family: cursive;
}
And now the HTML:
<h1>
Largest IPOs in US History
</h1>
<ul>
<li>2014: Alibaba - $20B</li>
<li>2008: Visa - $18B</li>
</ul>
The CSS selector targets and styles only the HTML element with the same name. For example, the preceding code is displayed in Figure 5-11. The heading “Largest IPOs in US History” was created using the opening and closing <h1> tag. It was styled with the h1 selector, where the font-family property with the cursive value is used to style only the text between the opening and closing <h1> tag, and not any items in the bulleted list. Font families are further described later in this chapter.
CSS lets you control text in many HTML elements. The most common text-related CSS properties and values are shown in Table 5-1. I describe these properties and values more fully in the sections that follow.
Table 5-1 Common CSS Properties and Values for Styling Text
Property name |
Possible values |
Description |
Example |
font-size |
pixels (#px) % em (#em) |
Specifies the size of text measured in pixels, as a percentage of the containing element’s font size, or with an em value, which is calculated by dividing the desired pixel value by the containing element’s font size in pixels. |
font-size: 16px; |
color |
name hex code rgb value |
Changes the color of the text specified using a name, a hexadecimal code, or RGB (red, green, and blue) value. |
color: blue; color: #0000FF; color: rgb(0,0,255); |
font-style |
normal italic |
Sets font to appear in italics (or not). |
font-style: italic; |
font-weight |
normal bold |
Sets font to appear as bold (or not). |
font-weight: bold; |
font-family |
font name |
Sets the font typeface. |
font-family: "serif"; |
You can set the size of the font you’re using with CSS’s font-size property. You have a few options for setting the font size, and the most common is to use pixels, as in the following:
p {
font-size: 16px;
}
In this example, I used the p selector to size the paragraph text to 16 pixels. Percentage sizing and em values, the other options to size your fonts, are considered more accessibility friendly because they scale and resize more accurately on various devices. The default browser font size for normal text is 16 pixels. With percentage sizing and em values, fonts can be sized relative to the user-specified default. For example, the CSS for percentage sizing looks like this:
p {
font-size: 150%;
}
In this example, I used the p selector to size the paragraph text to 150% of the default size. If the browser’s default font size was set at 16 pixels, this paragraph’s font would appear sized at 24 pixels (150% of 16).
The color property sets the color in one of three ways:
Following are examples of each of the three types of color changes:
p {
color: red
}
h1 {
color: #FF0000
}
h2 {
color: rgb(255,0,0)
}
In the first example, color: red, I set the paragraph color to red using the common color name . In the second example, I set the h1 color equal to #FF0000. After the hashtag (#), the first two digits (FF) refer to the red in the color, the next two digits (00) refer to the green in the color, and the final two digits (00) refer to the blue in the color. In the last example, color: rgb(255,0,0), each decimal value is separate by commas. The first decimal value of 255 is equivalent to the first two hexadecimal FF digits in the second example, and the second and third decimal values of 0 are equivalent to 00 in hexadecimal.
The font-style property can set text to italics, and the font-weight property can set text to bold. For each of these properties, the default is normal, which doesn’t need to be specified. In the following example, the paragraph is styled so that the font appears italicized and bold:
p {
font-style: italics;
font-weight: bold;
}
The font-family property sets the typeface used for text. The property is set equal to one font or to a list of fonts separated by commas. Your website visitors will have a variety of fonts installed on their computers, and the browser displays the first specified font in the font-family property only if that font is already installed on their system. If the font is not installed, the browser tries the remaining specified fonts until an installed font is found. If no specified fonts are installed, a default font is used.
The font-family property can be set equal to two types of values:
When using font-family, it’s best to define two or three specific fonts followed by a generic font family as a fallback in case the fonts you specify aren’t installed. For example:
p {
font-family: "Times New Roman", Helvetica, serif;
}
In this example, the paragraph’s font family is defined as Times New Roman. If Times New Roman isn’t installed on the user’s computer, the browser uses Helvetica. If Helvetica isn’t installed, the browser will use any available font in the generic serif font family.
JavaScript can be used to perform many tasks, from simple variable assignments to complex data visualizations. The following tasks, here explained in a JavaScript context, are core programming concepts that haven’t changed in the last twenty years and won’t change in the next twenty. They’re applicable to any programming language.
JavaScript can do any of the following:
JavaScript has a different structure and format than HTML and CSS and allows you to do more than position and style text on a web page. With JavaScript, you can store numbers and text for later use, decide what code to run based on conditions in your program, and even name pieces of your code so you can easily reference them later.
As with HTML and CSS, JavaScript has special keywords and syntax that allow the computer to recognize what you’re trying to do. Unlike HTML and CSS, however, JavaScript is intolerant of syntax mistakes. If you forget to close an HTML tag or to include a closing curly brace in CSS, your code may still run and your browser will try its best to display the code. When coding in JavaScript, on the other hand, forgetting a single quote or parenthesis can cause your entire program to fail to run.
The following code illustrates common punctuation used in JavaScript, specifically, semicolons, quotes, parentheses, and braces:
var age=22;
var planet="Earth";
if (age>=18)
{
console.log("You are an adult");
console.log("You are over 18");
}
else
{
console.log("You are not an adult");
console.log("You are not over 18");
}
General rules of thumb to know while programming in JavaScript include the following:
Variables, like those in algebra, are keywords used to store data values for later use. The variable name usually starts with a letter. Although the data stored in a variable may change, the variable name remains the same.
Think of a variable like a gym locker — what you store in the locker changes, but the locker number stays the same. Table 5-2 lists some types of data that JavaScript variables can store.
Table 5-2 Data Stored by a Variable
Data Type |
Description |
Examples |
Numbers |
Positive or negative numbers with or without decimals |
156 –101.96 |
Strings |
Printable characters |
Holly Novak Señor |
Boolean |
True or false value |
true false |
The first time you use a variable name, you use var to declare the variable name. Then you can optionally assign a value to variable using the equals sign. In the following code example, I declare three variables and assign values to those variables:
var myName="Nik";
var pizzaCost=10;
var totalCost=pizzaCost * 2;
After declaring a variable, you change its value by referring to just the variable name and using the equals sign, as shown in the following examples:
myName="Steve";
pizzaCost=15;
After you’ve stored data in a variable, it is common to compare the variable’s value to other variable values or to a fixed value, and then to make a decision based on the outcome of the comparison. In JavaScript, these comparisons are performed by using a conditional statement. The if-else statement is a type of conditional. Its general syntax is as follows:
if (condition) {
statement1 to execute if condition
is true
}
else {
statement2 to execute if condition
is false
}
In this statement, the if is followed by a space, and a condition enclosed in parentheses evaluates to true or false. If the condition is true, statement1, located between the first set of curly brackets, is executed. If the condition is false and I include else, which is optional, statement2, located between the second set of curly brackets, is executed. When the else is not included and the condition is false, the conditional statement simply ends.
The condition in an if-else statement is a comparison of values using operators. Common operators are described in Table 5-3.
Table 5-3 Common JavaScript Operators
Type |
Operator |
Description |
Example |
Less than |
< |
Evaluates whether one value is less than another value |
(x < 55) |
Greater than |
> |
Evaluates whether one value is greater than another value |
(x > 55) |
Equality |
=== |
Evaluates whether two values are equal |
(x === 55) |
Less than or equal to |
<= |
Evaluates whether one value is less than or equal to another value |
(x <= 55) |
Greater than or equal to |
>= |
Evaluates whether one value is greater than or equal to another value |
(x >= 55) |
Inequality |
!= |
Evaluates whether two values are not equal |
(x != 55) |
Here is a simple if statement, without the else:
var carSpeed=70;
if (carSpeed > 55) {
alert("You are over the speed limit!");
}
I declare a variable called carSpeed and set it equal to 70. Then an if statement with a condition compares whether the value in the variable carSpeed is greater than 55. If the condition is true, an alert (a pop-up box) states “You are over the speed limit!” In this case, the value of carSpeed is 70, which is greater than 55, so the condition is true and the alert is displayed. If the first line of code instead were var carSpeed=40;, the condition would be false because 40 is less than 55, and no alert would be displayed.
Let us expand the if statement by adding else to create an if-else, as shown in this code:
var carSpeed=40;
if (carSpeed > 55) {
alert("You are over the speed limit!");
}
else {
alert("You are under the speed limit!");
}
In addition to the else, I added an alert statement inside the curly brackets following the else, and set carSpeed equal to 40. When this if-else statement executes, carSpeed is equal to 40, which is less than 55, so the condition is false. Because the else has been added, an alert appears stating, “You are under the speed limit!”(See Figure 5-12) If the first line of code instead had been var carSpeed=70; as before, the condition would be true, because 70 is greater than 55, and the first alert would be displayed.
Our current if-else statement allows us to test for one condition, and to show different results depending on whether the condition is true or false. To test for two or more conditions, you can add one or more else if statements after the original if statement. The general syntax is as follows:
if (
condition1) {
statement1 to execute if condition1 is true
}
else if (
condition2) {
statement2 to execute if condition2 is true
}
else {
statement3 to execute if all previous conditions are false
}
The if-else is written as before, and the else if is followed by a space and a condition enclosed in parentheses that evaluates to either true or false. If condition1 is true, statement1 (located between the first set of curly brackets) is executed. If condition1 is false, condition2 is evaluated and is found to be either true or false. If condition2 is true, statement2 (located between the second set of curly brackets) is executed. At this point, additional else if statements could be added to test additional conditions.
As you can see, statement3 is executed only when all if and else if conditions are false and an else is included. Only one statement is executed in a block of code, after which the remaining statements are ignored and the next block of code is executed.
Here is another example else if statement:
var carSpeed=40;
if (carSpeed > 55) {
alert("You are over the speed limit!");
}
else if (carSpeed === 55) {
alert("You are at the speed limit!");
}
When this if statement executes, carSpeed is equal to 40, which is less than 55, so the condition is false, and then the else if condition is evaluated. The value of carSpeed is not exactly equal to 55, so this condition is also false; no alert is shown, and the statement ends.
If the first line of code were instead var carSpeed=55; the first condition would be false because 55 is not greater than 55. Then the else if condition would be evaluated, and because 55 is exactly equal to 55, the second alert would be displayed, stating “You are at the speed limit!”
The final example is an if-else statement with an else if statement:
var carSpeed=40;
if (carSpeed > 55) {
alert("You are over the speed limit!");
}
else if (carSpeed === 55) {
alert("You are at the speed limit!");
}
else {
alert("You are under the speed limit!");
}
As the diagram in Figure 5-13 shows, two conditions, which appear in the figure as diamonds, are evaluated in sequence. In this example, carSpeed is equal to 40, so the two conditions are false, and the statement after the else is executed, showing the alert, “You are under the speed limit!” Here carSpeed is initially set to 40, but depending on the initial carSpeed variable value, any one of the three alerts could be displayed.
The most basic data types are strings and numbers. They are usually stored in variables. Programmers often need to manipulate strings and numbers to perform basic tasks, such as the following:
Tasks like these are so common that JavaScript includes shortcuts called methods that make performing these tasks easier. The general syntax to perform these tasks is to follow the affected variable’s name or value with a period and the name of the method, as follows for values and variables:
value.method;
variablename.method;
Table 5-4 shows examples of JavaScript methods applied to values, such as strings, and to variables.
Table 5-4 Common JavaScript Methods
Method |
Description |
Example |
Result |
.toFixed(n) |
Rounds a number to n decimal places |
var jenny=8.675309; jenny.toFixed(2); |
8.68 |
.length |
Represents the number of characters in a string |
"Nik".length; |
3 |
Displaying messages to the user and collecting input are the beginnings of the interactivity that JavaScript provides. Although more sophisticated techniques exist, the alert() method and prompt() method are easy ways to show a pop-up box with a message and prompt the user for input.
The syntax for creating an alert or a prompt is to write the method with text in quotes placed inside the parentheses, like so:
alert("You have mail");
prompt("What do you want for dinner?");
Figure 5-14 shows the alert pop-up box created by the alert() method and the prompt for user input created by the prompt() method.
You can practice your HTML, CSS, and JavaScript online by using the Codecademy website. Codecademy is a free website created in 2011 to allow anyone to learn how to code right in the browser, without installing or downloading any software. Practice the tags and commands that you learned in this chapter by following these steps:
www.codecademy.com
.Sign up for or sign into your Codecademy account.
Creating an account is optional, but doing so means you can save your work. To use the website without creating an account, scroll down the bottom of the page, and click the lessons under the Learn to Code heading.
Under the Language Skills section, click the HTML & CSS card or the JavaScript card, and then click a lesson.
You see background information in the upper-left part of the screen and instructions in the lower left.
A green check mark appears and you can proceed to the next exercise.
If your code has an error, a warning appears with a suggested fix. If you run into a problem or have a bug you can’t fix, click the hint, use the Q&A forums, or tweet me at @nikhilgabraham and include hashtag #codingFD.