Chapter 5

Creating a Website

In This Chapter

arrow Understanding what HTML, CSS, and JavaScript do

arrow Learning to do common HTML and CSS tasks

arrow 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.

What Do HTML, CSS, and JavaScript Do?

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.

image

Figure 5-1: The layout of a word processor.

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.

remember HTML files are plain text files that appear styled only when viewed with a browser.

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.

image

Figure 5-2: Facebook with CSS (left) and without (right).

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).

image

Figure 5-3: JavaScript can create the date picker found on travel websites.

technicalstuff JavaScript is different from another programming language called Java. In 1996, Brendan Eich, at the time a Netscape engineer, created LiveScript. As part of a marketing decision, LiveScript was renamed to JavaScript to try and benefit from the reputation of the then-popular Java.

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).

image

Figure 5-4: Gmail uses AJAX, which lets users read new emails without reloading the web page.

tip Before AJAX, the browser would display new data on a web page only after waiting for the entire web page to reload. This technique slowed down the user experience, especially when viewing web pages with frequent real — time updates, such as news, sports updates, and stock information. With AJAX, the browser could communicate with a server in the background, and update the current web page with new information.

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.

Common HTML Tasks and Tags

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:

  • The element is a letter, word, or phrase with special meaning. For example, h1 is an element that applies a header effect, with bold text and a large font size.
  • The element is enclosed with a left-angle bracket (<) and a right-angle bracket (>), such as <h1>. An element enclosed in this way is called a tag.
  • An opening tag (such as <h1>) is followed by a closing tag (</h1>). Note that the closing tag differs from the opening tag by the addition of a forward slash after the first left bracket and before the element.

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.

image

Figure 5-5: The example code displayed in a browser.

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 browser recognizes the h1 element.
  • The h1 element is surrounded with a left (<) and right angle bracket (>).
  • The opening tag (<h1>) is followed by text and a closing tag (</h1>).

tip Note how the h1 tag itself does not appear in the heading. The browser only displays text between a properly formatted opening and closing HTML tag.

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.

remember Every left-angle bracket must be followed after the element with a right-angle bracket. In addition, every opening HTML tag must be followed with a closing HTML tag.

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.

image

Figure 5-6: A New York Times article with headline, para-graphs, hyperlinks, and images.

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:

  • Headlines: Headlines are displayed in bold and have a larger font size than the surrounding text.
  • Paragraphs: Each story is organized into paragraphs with white space dividing each paragraph.
  • Hyperlinks: The site’s home page and article pages have links to other stories, as well as links to share the story on social networks such as Facebook, Twitter, and Google+.
  • Images: Writers place images throughout the story. Also look for site images such as icons and logos.

In the following sections I explain how to write code to create these common HTML features.

Writing headlines

Use headlines to describe a section of your page. HTML has six levels of headings:

  • h1, which is used for the most important headings
  • h2, which is used for subheadings
  • h3 to h6, which are used for less important 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.

image

Figure 5-7: Headings created using elements h1 through h6.

remember Always close what you open. With headings, remember to include a closing heading tag, such as </h1>.

Organizing text in paragraphs

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.

tip To insert a single line break after any element, use the <br> tag. The <br> tag is self-closing, so no closing tag is used.

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.

image

Figure 5-8: Text displayed in paragraphs using the p element.

Linking to your (heart’s) content

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:

  • Link destination: The web page the browser visits after the link is clicked. The link destination can be for another section of the same page or to another external web page.
  • Link description: The words used to describe the link, which are more readable and descriptive than the link destination.

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.

image

Figure 5-9: Three hyperlinks created using the a element.

When rendering a hyperlink, the browser underlines the link and colors it blue by default.

technicalstuff Google’s search engine ranks web pages on many factors but primarily based on the words used to describe a web page between the opening and closing <a> tags. This method was a big improvement over previous search-indexing methods, which tried to analyze an individual web page’s content.

Adding images

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.

tip If you want to use an image that has not already been uploaded to the Internet, you can use a site such as www.imgur.com to upload the image. After uploading, you will be able to copy the image URL and use it in your HTML.

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.

image

Figure 5-10: Images of Grace Hopper and Bill Gates rendered using <img>.

tip The image tag is self-closing, so you don’t use a separate </img> closing image tag. The image tag is one of the exceptions to the always-close-what-you-open rule!

Common CSS Tasks and Selectors

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:

  • Text size, color, style, typeface, and alignment
  • Link color and style
  • Image size and alignment

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:

  • Selector: The HTML element you want to style.
  • Property: The feature of the HTML element you want to style, such as font typeface, image height, or color.
  • Value: The options for the property that the CSS rule sets. For example, if color is the property, the value might be red.

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.

tip Looking for curly braces on your keyboard? Most keyboards have the left and right curly brace to the right of the P key. Make sure you choose the curly braces and not the square brackets, which are on the same key.

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.

image

Figure 5-11: CSS targeting the heading h1 element.

remember CSS uses a colon instead of the equals sign (=) to set values against properties. Multiple values for the same property are separated using a comma, and a semicolon is placed after the final value.

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";

Setting the font size

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).

technicalstuff A font-size equal to 1px is equivalent to one pixel on your monitor, so the size of the text displayed varies according to the size of the monitor. Accordingly, for a fixed font size in pixels, the text appears smaller as you increase the screen resolution.

Setting the color

The color property sets the color in one of three ways:

  • Name: You can reference 147 colors by name, including common colors, such as black, blue, and red, as well as uncommon colors, such as burlywood, lemon chiffon, and thistle.
  • Hex code: You can define more than 16 million colors by using hexadecimal code to specify their component parts of red, green, and blue.
  • RGB value: Just like hex codes, RGB values specify the red, green, and blue component parts for over 16 million colors. RGB values are the decimal equivalent to hexadecimal values.

tip Don’t worry about trying to remember hex codes or RGB values. You can easily identify colors using an online color picker such as the one at www.w3schools.com/tags/ref_colorpicker.asp .

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.

tip All three colors in the preceding example reference the same shade of red. For the full list of colors that can be referenced by name, go to www.w3.org/TR/css3-color/#svg-color.

Setting the font style and font weight

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;

}

Setting the font family

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:

  • Font name: Specific font names such as Times New Roman, Arial, and Courier.
  • Generic font family: Modern browsers usually define one installed font for each generic font family:
    • serif (such as Times New Roman or Palatino)
    • sans-serif (such as Helvetica or Verdana)
    • monospace (such as Courier or Andale Mono)
    • cursive (such as Comic Sans or Florence)
    • fantasy (such as Impact or Oldtown)

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.

tip When using a font name with multiple words (such as Times New Roman) enclose the font name in quotes.

Common JavaScript Tasks and Commands

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:

  • Control web page appearance and layout by changing HTML attributes and CSS styles
  • Easily create web page elements such as date pickers and drop-down menus
  • Take user input in forms, and check for errors before submission
  • Display and visualize data using complex charts and graphs
  • Import and analyze data from other websites

Understanding JavaScript structure

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.

remember HTML specifies the content type and applies an effect to the text between opening and closing tags. For example, the HTML code <h1>This is a header</h1> signals that the text between the two tags is a text header. CSS styles the HTML element using properties and values between opening and closing curly braces. For example, the CSS code h1 { color: red;} styles the text header to be the color red.

Using semicolons, quotes, parentheses, and braces

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:

  • Semicolons separate JavaScript statements.
  • Quotes enclose text characters or strings (sequences of characters). Any opening quote must have a closing quote.
  • Parentheses are used to modify commands with additional information called arguments. Any opening parenthesis must have a closing parenthesis.
  • Braces group JavaScript statements into blocks so that they execute together. Any opening brace must have a closing brace.

tip These syntax rules can seem arbitrary and may be difficult to remember initially. With some practice, however, the rules will feel like second nature to you.

Storing data with variables

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

technicalstuff For a list of rules on variable names, see the “JavaScript Variables” section at www.w3schools.com/js/js_variables.asp.

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;

technicalstuff Programmers say you have declared a variable when you first define it using the var keyword. Declaring a variable tells the computer to reserve space in memory and permanently store values using the variable name. You can view these values by using the console.log statement. For example, after running the preceding code, typing the statement console.log(totalCost) would return the value 20.

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;

remember Variable names are case sensitive, so when referring to a variable in your program, remember that MyName, for example, is a different variable than myname. In general, it’s a good idea to give your variable a name that describes the data being stored.

Making decisions with if-else statements

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.

tip Note there are no parentheses after the else — the else line has no condition. JavaScript executes the statement after else only when the preceding conditions are false.

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.

image

Figure 5-12: JavaScript alert for an if-else statement.

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.

tip When writing the if-else, you must have one and only one if statement; you may have only one else statement if you choose to include one. The else if is optional, can be used multiple times in a single if-else statement, and must come after the original if statement and before the else. You cannot have an else if or an else by itself, without a preceding if statement.

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!”

remember Look carefully at the preceding code. When setting the value of a variable, you use one equals sign. But when comparing whether two values are equal, you use three equals signs (===).

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.

image

Figure 5-13: If-else with an else if statement.

remember The condition is always evaluated first, and every condition must either be true or false. Independent from the condition is the statement that executes if the condition is true.

Working with string and number methods

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:

  • Rounding a number to a fixed numbers of decimal points, such as when getting a subtotal in an online shopping cart, calculating the tax, rounding the tax to two decimal points, and adding the tax to the subtotal
  • Determining the length of a string, such as for a password

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

remember When using a string, or assigning a variable to a value that is a string, always enclose the string in quotes.

tip For a list of additional string and number methods see W3Schools at www.w3schools.com/js/js_number_methods.asp and www.w3schools.com/js/js_string_methods.asp.

Alerting users and prompting for input

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.

image

Figure 5-14: A Java-Script alert pop-up box and a user prompt.

Practicing Your HTML, CSS, and JavaScript

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:

  1. Open your browser, and go to www.codecademy.com.
  2. 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.

  3. 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.

  4. Complete the instructions in the main coding window.

    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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.74.66