Adding in JavaScript - Building the Silent and Interactive Web Page - Coding For Dummies (2015)

Coding For Dummies (2015)

Part II. Building the Silent and Interactive Web Page

Chapter 9. Adding in JavaScript

In This Chapter

arrow Understanding JavaScript basics and structure

arrow Coding with variables, conditional statements, and functions

arrow Learning about API basics and structure

arrow Viewing an API request and response

The best teacher is very interactive.

—Bill Gates

JavaScript, one of the most popular and versatile programming languages on the Internet, adds interactivity to websites. You have probably seen JavaScript in action and not even realized it, perhaps while clicking buttons that change color, viewing image galleries with thumbnail previews, or analyzing charts that display customized data based on your input. These website features and more can be created and customized using JavaScript.

JavaScript is an extremely powerful programming language, and this entire book could have been devoted to the topic. In this chapter, you learn JavaScript basics, including how to write JavaScript code to perform basic tasks, access data using an API, and program faster using a framework.

What Does JavaScript Do?

JavaScript creates and modifies web page elements, and works with the existing web page HTML and CSS to achieve these effects. When you visit a web page with JavaScript, your browser downloads the JavaScript code and runs it client-side, on your machine. JavaScript can perform tasks to do any of the following:

· Control web page appearance and layout by changing HTML attributes and CSS styles.

· Easily create web page elements like date pickers, as shown in Figure 9-1, 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.

9781118951309-fg0901.tif

Figure 9-1: JavaScript can create the date picker found on every travel website.

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

JavaScript was created almost 20 years ago, and the language has continued to evolve since then. 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), probably sounds trivial, but has led to the creation of cutting-edge browser experiences such as Gmail (shown in Figure 9-2).

Before AJAX, the browser would display new data on a web page only after waiting for the entire web page to reload. However, this slowed down the user experience, especially when viewing web pages which had frequent real time updates like web pages with news stories, sports updates, and stock information. JavaScript, specifically AJAX, created a way for your browser to communicate with a server in the background, and to update your current web page with this new information.

9781118951309-fg0902.tif

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

tip.eps Here is an easy way to think about AJAX: Imagine you are at a coffee shop, and just ordered a coffee after waiting in a really long line. Before asynchronous JavaScript, you had 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.

Understanding JavaScript Structure

JavaScript has a different structure and format from HTML and CSS. JavaScript 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 within 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 are 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 your code. When coding in JavaScript, on the other hand, forgetting a single quote or parenthesis can cause your entire program to fail to run at all.

remember.eps HTML applies an effect between opening and closing tags — <h1>This is a header</strong>. CSS uses the same HTML element and has properties and values between opening and closing curly braces — h1 { color: red;}.

Using Semicolons, Quotes, Parentheses, and Braces

The code below illustrates the common punctuation used in JavaScript — semicolons, quotes, parentheses, and braces (also called curly brackets):

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:

· 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 they execute together. Any opening brace must have a closing brace.

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

Coding Common JavaScript Tasks

JavaScript can be used to perform many tasks, from simple variable assignments to complex data visualizations. The following tasks, here explained within 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. Finally, I’ve listed instructions on how to perform these tasks, but if you prefer you can also practice these skills right away by jumping ahead to the “Writing Your First JavaScript Program” section, later in this chapter.

Storing data with variables

Variables, like those in algebra, are keywords used to store data values for later use. Though 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 always stays the same. The variable name usually starts with a letter, and Table 9-1 lists some types of data JavaScript variables can store.

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

Table 9-1 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 NovakSeñor

Boolean

Value can either be true or false.

truefalse

The first time you use a variable name, you use the word 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.eps 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 to permanently store values using the variable name. View these values by using the console.logstatement. For example, after running the preceding example code, running statement console.log(totalCost) returns 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;

tip.eps Variable names are case sensitive, so when referring to a variable in your program remember that MyName is a different variable from 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 have 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 done using a conditional statement. The if-elsestatement 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, then statement1, located between the first set of curly brackets, is executed. If the condition is false and if I include the else, which is optional, then statement2, located between the second set of curly brackets, is executed. Note that when the else is not included and the condition is false, the conditional statement simply ends.

tip.eps Notice 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, and common operators are described in Table 9-2.

0902

Here is a simple if statement, without the else:

var carSpeed=70;
if (carSpeed > 55) {
alert("You are over the speed limit!");
}

In this statement 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, which is a pop-up box, states “You are over the speed limit!” (See Figure 9-3.) 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 was var carSpeed=40; then the condition is false because 40 is less than 55, and no alert would be displayed.

9781118951309-fg0903.tif

Figure 9-3: The alert pop-up box.

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, and because the else has been added, an alert appears stating “You are under the speed limit!” If the first line of code instead was var carSpeed=70; as before, then the condition is 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 for this 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 then a condition enclosed in parentheses that evaluates to either true or false. If condition1 is true, then statement1, located between the first set of curly brackets, is executed. If thecondition1 is false, then condition2 is evaluated and is found to be either true or false. If condition2 is true, then 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. Only when all if and else if conditions are false, and an else is included, is statement3 executed. 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.eps When writing the if-else, you must have one and only one if statement, and, if you so choose, one and only one else statement. The else if is optional, can be used multiple times within 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, and no alert of any kind is shown, and the statement ends. If the first line of code were instead var carSpeed=55; then the first condition is false, because 55 is not greater than 55. Then the else if condition is evaluated, and because 55 is exactly equal to 55, the second alert is displayed, stating “You are at the speed limit!”

remember.eps Look carefully at the code above —- when setting the value of a variable, one equals sign is used, but when comparing whether two values are equal, then three equals signs (===) are used.

As a final example, here 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 9-4 shows, two conditions, which appear in the figure as diamonds, are evaluated in sequence. In this example, the carSpeed is equal to 40, so the two conditions are false, and the statement after the else is executed, showing an alert that says “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.

9781118951309-fg0904.tif

Figure 9-4: If-else with an else if statement.

remember.eps 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, usually stored in variables, are strings and numbers. Programmers often need to manipulate strings and numbers to perform basic tasks such as the following:

· Determining the length of a string, as for a password.

· Selecting part (or substring) of a string, as when choosing the first name in a string that includes the first and last name.

· Rounding a number to fixed numbers of decimal points, as when taking a subtotal in an online shopping cart, calculating the tax, rounding the tax to two decimal points, and adding the tax to the subtotal.

These tasks are so common that JavaScript includes shortcuts called methods (italicized above) that make performing tasks like these 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;
variable.method;

Table 9-3 shows examples of JavaScript methods for the basic tasks discussed above. Examples include methods applied to values, such as strings, and to variables.

0903

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

The .toFixed and .length methods are relatively straightforward, but the .substring method can be a little confusing. The starting and ending positions used in .substring(start, end) do not reference actual characters, but instead reference the space between each character. Figure 9-5 shows how the start and end position works. The statement "Inbox".substring(2,5) starts at position 2, which is between "n" and "b", and ends at position 5 which is after the "x".

9781118951309-fg0905.tif

Figure 9-5: The .substring method references positions that are between characters in a string.

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

Alerting users and prompting them for input

Displaying messages to the user and collecting input are the beginnings of the interactivity that JavaScript provides. Although more sophisticated techniques exist today, 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 9-6 shows the alert pop-up box created by the alert() method, and the prompt for user input created by the prompt() method.

9781118951309-fg0906.tif

Figure 9-6: A JavaScript alert pop-up box and a user prompt.

Naming code with functions

Functions are a way of grouping JavaScript statements, and naming that group of statements for easy reference with a function name. These statements are typically grouped together because they achieve a specific coding goal. You can use the statements repeatedly by just writing the function name instead of having to write the statements over and over again. Functions prevent repetition and make your code easier to maintain.

When I was younger every Saturday morning my mother would tell me to brush my teeth, fold the laundry, vacuum my room, and mow the lawn. Eventually, my mother tired of repeating the same list over and over again, wrote the list of chores on paper, titled it “Saturday chores,” and put it on the fridge. A function names a group of statements, just like “Saturday chores” was the name for my list of chores.

Functions are defined once using the word function, followed by a function name, and then a set of statements inside curly brackets. This is called a function declaration. The statements in the function are executed only when the function is called by name. In the following example, I have declared a function called greeting that asks for your name using the prompt() method, returns the name you entered storing it in a variable called name, and displays a message with the name variable using the alert() method:

function greeting() {
var name=prompt("What is your name?");
alert("Welcome to this website " + name);
}

greeting();
greeting();

Beneath the function declaration, I have called the function twice, and so I will trigger two prompts for my name, which are stored in the variable name, and two messages welcoming the value in the variable name to this website.

tip.eps The “+” operator is used to concatenate (combine) strings with other strings, values, or variables.

Functions can take inputs, called parameters, to help the function run, and can return a value when the function is complete. After writing my list of chores, each Saturday morning my mother would say “Nik, do the Saturday chores,” and when my brother was old enough she would say “Neel, do the Saturday chores.” If the list of chores is the function declaration, and “Saturday chores” is the function name, then “Nik” and “Neel” are the parameters. Finally, after I was finished, I would let my mom know the chores were complete, much as a function returns values.

In the following example, I have declared a function called amountdue, which takes price and quantity as parameters. The function, when called, calculates the subtotal, adds the tax due, and then returns the total. The function amountdue(10,3) returns 31.5.

function amountdue(price, quantity) {
var subtotal=price * quantity;
var tax = 1.05;
var total = subtotal * tax;
return total;
}

alert("The amount due is $" + amountdue(10,3));

remember.eps Every opening parenthesis has a closing parenthesis, every opening curly bracket has a closing curly bracket, and every opening double quote has a closing double quote. Can you find all the opening and closing pairs in the example above?

Adding JavaScript to the web page

The two ways to add JavaScript to the web page are:

· Embed JavaScript code in an HTML file using the script tag.

· Link to a separate JavaScript file from the HTML file using the script tag.

To embed JavaScript code in an HTML file, use an opening and closing <script> tag, and write your JavaScript statements between the two tags, as shown in the following example:

<!DOCTYPE html>
<html>
<head>
<title>Embedded JavaScript</title>
<script>
alert("This is embedded JavaScript");
</script>
</head>
<body>
<h1>Example of embedded JavaScript</h1>
</body>
</html>

tip.eps The <script> tag can be placed inside the opening and closing <head> tag, as shown above, or inside the opening and closing <body> tag. There are some performance advantages when choosing one approach over the other, and you can read more athttp://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup.

The <script> tag is also used when linking to a separate JavaScript file, which is the recommended approach. The <script> tag includes:

· A type attribute, which for JavaScript is always set equal to "text/javascript"

· A src attribute, which is set equal to the location of the JavaScript file.

<!DOCTYPE html>
<html>
<head>
<title>Linking to a separate JavaScript file</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Linking to a separate JavaScript file</h1>
</body>
</html>

remember.eps The <script> tag has an opening and closing tag, whether the code is embedded between the tags or linked to separate file using the src attribute.

Writing Your First JavaScript Program

Practice your JavaScript online 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 all of the tags (and a few more) that you learned in this chapter by following these steps:

1. Open your browser, go to www.dummies.com/go/codingfd, and click on the link to Codecademy.

2. Sign in to your Codecademy account.

Signing up is discussed in Chapter 3. Creating an account allows you to save your progress as you work, but it’s optional.

3. Navigate to and click on Getting Started with Programming.

4. Background information is presented in the upper left portion of the site, and instructions are presented in the lower left portion of the site.

5. Complete the instructions in the main coding window.

6. After you have finished completing the instructions, click the Save and Submit Code button.

If you have followed the instructions correctly, a green checkmark appears and you proceed to the next exercise. If an error exists in your code a warning appears with a suggested fix. If you run into a problem, or have a bug you cannot fix, click on the hint, use the Q&A Forums, or tweet me at @nikhilgabraham and include hashtag #codingFD.

Working with APIs

Although APIs (application programming interfaces) have existed for decades, the term has become popular over the last few years as we hear more conversation and promotion around their use. Use the Facebook API! Why doesn’t Craigslist have an API? Stripe’s entire business is to allow developers to accept payments online using its payments API.

Many people use the term API, but few understand its meaning. This section will help clarify what APIs do and how they can be used.

What do APIs do?

An API allows Program A to access select functions of another separate Program B. Program B grants access by allowing Program A to make a data request in a structured, predictable, documented way, and Program B responds to this data request with a structured, predictable, documented response, as follows (see Figure 9-7):

· It’s structured because the fields in the request and the data in the response follow an easy-to-read standardized format. For example, the Yahoo Weather API data response includes these selected structured data fields:

"location": {
"city": "New York",
"region": "NY"
},
"units": {
"temperature": "F"
},
"forecast": {
"date": "29 Oct 2014",
"high": "68",
"low": "48",
"text": "PM Showers"
}

tip.eps See the full Yahoo Weather API response by visiting http://developer.yahoo.com/weather/.

· It’s predictable because the fields that must be included and can be included in the request are pre-specified, and the response to a successful request will always include the same field types.

· It’s documented because the API is explained in detail. Any changes usually are communicated through the website, social media, email, and even after the API changes, there is often a period of backward compatibility when the old API requests will receive a response. For example, when Google Maps issued version 3 of their API, version 2 still operated for a certain grace period.

9781118951309-fg0907.tif

Figure 9-7: An API allows two separate programs to talk to each other.

Above you saw a weather API response, so what would you include in a request to a weather API? The following fields are likely important to include:

· Location, which can potentially be specified by using zip code, city and state, current location in latitude and longitude coordinates, or IP address.

· Relevant time period, which could include the instant, daily, three day, weekly, or 10-day forecast.

· Units for temperature (Fahrenheit or Celsius) and precipitation (inches or centimeters).

remember.eps These fields in our request just specify the desired type and data format. The actual weather data would be sent after the API knows your data preferences.

Can you think of any other factors to consider when making the request? Here is one clue — imagine you work for Al Roker on NBC’s Today TV show, and you are responsible for updating the weather on the show’s website for 1 million visitors each morning. Meanwhile, I have a website, NikWeather, which averages 10 daily visitors who check the weather there. The Today website and my website both make a request to the same weather API at the same time. Who should receive their data first? It seems intuitive that the needs of 1 million visitors on the Todaywebsite should outweigh the needs of my website’s 10 visitors. An API can prioritize which request to serve first, when the request includes an API key. An API key is a unique value, usually a long alpha-numeric string, which identifies the requestor and is included in the API request. Depending on your agreement with the API provider, your API key can entitle you to receive prioritized responses, additional data, or extra support.

Can you think of any other factors to consider when making the request? Here is another clue — is there any difference in working with weather data versus financial data? The other factor to keep in mind is frequency of data requests and updates. APIs will generally limit the number of times you can request data. In the case of a weather API, maybe the request limit is once every minute. Related to how often you can request the data is how often the data is refreshed. There are two considerations — how often the underlying data changes, and how often the API provider updates the data. For example, except in extreme circumstances the weather generally changes every 15 minutes. Our specific weather API provider may update its weather data every 30 minutes. Therefore, you would only send an API request once every 30 minutes, because sending more frequent requests wouldn’t result in updated data. By contrast, financial data such as stock prices and many public APIs, which change multiple times per second, allow one request per second.

Scraping data without an API

In the absence of an API, those who want data from a third-party website create processes to browse the website, search and copy data, and store it for later use. This method of data retrieval is commonly referred to as screen scraping or web scraping. These processes, which vary in sophistication from simple to complex, include:

· People manually copying and pasting data from websites into a database: Crowdsourced websites, such as www.retailmenot.com recently listed on the NASDAQ stock exchange, obtain some data in this way.

· Code snippets written to find and copy data that match pre-set patterns: The pre-set patterns are also called regular expressions, which match character and string combinations, and can be written using web languages like JavaScript or Python.

· Automated software tools which allow you to point and click the fields you want to retrieve from a website: For example, www.kimonolabs.com is one point-and-click solution, and when FIFA World Cup 2014 lacked a structured API, kimonolabs.com extracted data, such as scores, and made it easily accessible.

The advantage of screen scraping is that the data is likely to be available and with less restrictions because it is content that regular users see. If an API fails, it may go unnoticed and depending on the site take time to fix. By contrast, the main website failing is usually a top priority item, and fixed as soon as possible. Additionally, companies may enforce limits on data retrieved from the API that are rarely seen and harder to enforce when screen scraping.

The disadvantage of screen scraping is that the code written to capture data from a website must be precise and can break easily. For example, a stock price is on a web page in the second paragraph, on the third line, and is the fourth word. The screen scraping code is programmed to extract the stock price from that location, but unexpectedly the website changes its layout so the stock price is now in the fifth paragraph. Suddenly, the data is inaccurate. Additionally, there may be legal concerns with extracting data in this way, especially if the website terms and conditions prohibit screen scraping. In one example, Craigslist terms and conditions prohibited data extraction through screen scraping, and after litigation a court banned a company which accessed Craigslist data using this technique.

Researching and choosing an API

For any particular data task there may be multiple APIs that can provide you with the data you seek. The following are some factors to consider when selecting an API for use in your programs:

· Data availability: Make a wish list of fields you want to use with the API, and compare it to fields actually offered by various API providers.

· Data quality: Benchmark how various API providers gather data, and the frequency with which the data is refreshed.

· Site reliability: Measure site uptime because regardless of how good the data may be, the website needs to stay online to provide API data. Site reliability is a major factor in industries like finance and healthcare.

· Documentation: Review the API documentation for reading ease and detail so you can easily understand the API features and limitations before you begin.

· Support: Call support to see response times and customer support knowledgeability. Something will go wrong and when it does you want to be well supported to quickly diagnose and solve any issues.

· Cost: Many APIs provide free access below a certain request threshold. Investigate cost structures if you exceed those levels so you can properly budget for access to your API.

Using JavaScript Libraries

A JavaScript library is pre-written JavaScript code that makes the development process easier. The library includes code for common tasks that has already been tested and implemented by others. To use the code for these common tasks, you only need to call the function or method as defined in the library. Two of the most popular JavaScript libraries are jQuery and D3.js.

jQuery

jQuery uses JavaScript code to animate web pages by modifying CSS on the page, and to provide a library of commonly used functions. Although you could write JavaScript code to accomplish any jQuery effect, jQuery’s biggest advantage is completing tasks by writing fewer lines of code. As the most popular JavaScript library today, jQuery is used on the majority of top 10,000 most visited websites. Figure 9-8 shows a photo gallery with jQuery transition image effects.

D3.js

D3.js is a JavaScript library for visualizing data. Just like with jQuery, similar effects could be achieved using JavaScript, but only after writing many more lines of code. The library is particularly adept at showing data across multiple dimensions, and creating interactive visualizations of datasets. The creator of D3.js is currently employed at The New York Times, which extensively uses D3.js to create charts and graphs for online articles. Figure 9-9 is an interactive chart showing technology company IPO value and performance over time.

9781118951309-fg0908.tif

Figure 9-8: Photo gallery with jQuery transition image effects triggered by navigation arrows.

9781118951309-fg0909.tif

Figure 9-9: An IPO chart showing the valuation of the Facebook IPO relative to other technology IPOs.

Searching for Videos with YouTube’s API

Practice accessing APIs 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 all of the tags (and a few more) that you learned in this chapter by following these steps:

1. Open your browser, go to www.dummies.com/go/codingfd, and click on the link to Codecademy.

2. Sign in to your Codecademy account.

Signing up is discussed in Chapter 3. Creating an account allows you to save your progress as you work, but it’s optional.

3. Navigate to and click on How to use APIs with JavaScript, and then Searching for YouTube Videos.

4. Background information is presented in the upper left portion of the site, and instructions are presented in the lower left portion of the site.

5. Complete the instructions in the main coding window.

6. After you have finished completing the instructions, click the Save and Submit Code button.

If you have followed the instructions correctly, a green checkmark appears and you proceed to the next exercise. If an error exists in your code a warning appears with a suggested fix. If you run into a problem, or have a bug you cannot fix, click on the hint, use the Q&A Forums, or tweet me at @nikhilgabraham and include hashtag #codingFD.