Coding and Debugging Your First Web Application - Putting Together a Web Application - Coding For Dummies (2015)

Coding For Dummies (2015)

Part III. Putting Together a Web Application

Chapter 12. Coding and Debugging Your First Web Application

In This Chapter

arrow Reviewing code to see pre-existing functionality

arrow Writing code by following steps to create your app

arrow Debugging your code by looking for common syntax errors

Talk is cheap. Show me the code.

—Linus Torvalds

It may not feel like it, but you’ve already done the majority of work toward creating your first web application. You painfully broke down your app into steps, and researched each step to determine functionality and design. As Linus Torvalds, creator of the Linux operator system, said, “Talk is cheap.” So let’s start actually coding.

Getting Ready to Code

Before you start coding, do a few housekeeping items. First, ensure that you are doing all of the following:

· Using the Chome browser: Download and install the latest version of Chome, as it offers the most support for the latest HTML standards, and is available for download at www.google.com/chrome/browser.

· Working on a desktop or laptop computer: Although it is possible to code on a mobile device, it can be more difficult and all layouts may not appear properly.

· Remembering to indent your code to make it easier to read: One main source of mistakes is forgetting to close a tag or curly brace, and indenting your code will make spotting these errors easier.

· Remembering to enable location services on your browser and computer: To enable location services within Chrome, click on the settings icon (3 horizontal lines on the top right of the browser), and click on Settings. Then click on the Settings tab, and at the bottom of the screen click on “Show Advanced settings … ” Under the Privacy menu heading, click on “Content settings … ” and scroll down to Location and make sure that “Ask when a site tries to track your physical location” is selected. You can read more heresupport.google.com/chrome/answer/142065.

To enable location services on a PC no additional setting is necessary, but on a Mac using OS X Mountain Lion or later, from the Apple menu choose System Preferences, then click on the Security & Privacy icon, and click the Privacy tab. Click the padlock icon on the lower left, and select Location Services, and check Enable Location Services. You can read more here support.apple.com/en-us/ht5403.

Finally, you need to set up your development environment. To emulate a development environment without instructional content use Codepen.io. Codepen.io offers a free stand-alone development environment, and makes it easy to share your code. Open this URL in in your browser:codepen.io/nabraham/pen/ExnsA.

Coding Your First Web Application

With the Codepen.io URL loaded, let us review the development environment, the pre-written code, and the coding steps for you to follow.

Development environment

The Codepen.io development environment, as shown in Figure 12-1, has three coding panels, one each for HTML, CSS, and JavaScript. There is also a preview pane to see the live results of your code. Using the button at the bottom of the screen, you can hide any coding panel you aren’t using, and the layout of the coding panels can be changed.

Signing up for a Codepen.io account is completely optional, and allows you to fork or save the code you have written, and share it with others.

9781118951309-fg1201.tif

Figure 12-1: The Codepen.io development environment.

Pre-written code

The Codepen.io development environment includes some pre-written HTML, CSS, and JavaScript code for the McDuck’s app. The pre-written code includes code you have seen in previous chapters, and new code that is explained below:

· HTML: The HTML code for the McDuck’s app is below, and includes

· Two sections: an opening and closing <head> tag, and an opening and closing <body> tag.

· Inside the <body> tags are <h1> tags to create a heading and <div> tags.

· Additional <div> tags to display messages created in the JavaScript file. The <div> tag is a container that can hold content of any type. The first <div> tag is used to display your current longitude and latitude. The second <div> tag can be used to display additional content to the user.

· Instructions to insert the HTML button and onclick attribute code, which you researched in previous chapters.

Here’s the HTML code:

<!DOCTYPE html>
<html>
<head>
<title>McDuck's App</title>
</head>
<body>
<h1> McDuck's Local Offers</h1>
<!--1. Create a HTML button that when clicked calls the JavaScript getLocation() function -->

<!--Two containers, called divs, used to show messages to user -->

<div id="geodisplay"></div>
<div id="effect"></div>

</body>
</html>

· CSS: The CSS code for the McDuck’s app is below, and includes:

· Selectors for the body, heading, and paragraph tags.

· Properties and values that set the text alignment, background color, font family, font color, and font size.

Once your app is functioning, style the app by adding a McDuck’s color scheme and background image logo.

Here’s the CSS:

body {
text-align: center;
background: white;
}

h1, h2, h3, p {
font-family: Sans-Serif;
color: black;
}

p {
font-size: 1em;
}

· JavaScript: The JavaScript code for the McDuck’s app is below. This pre-written code is a little complex, because it calculates the current location of the user using the HTML Geolocation API. In this section I review the code at a high level so you can understand how it works and where it came from.

The Geolocation API is the product of billions of dollars of research and is available to you for free. The most recent browsers support geolocation, though some older browsers do not. At a basic level, code is written to ask whether the browser supports the Geolocation API, and, if yes, to return the current location of the user. When called, the Geolocation API balances a number of data inputs to determine the user’s current location. These data inputs include GPS, wireless network connection strength, cell tower and signal strength, and IP address.

With this in mind, let’s look at the JavaScript code. The JavaScript code includes two functions, as follows:

· The getLocation() function:This function determines whether the browser supports geolocation. It does this by using an if statement and navigator.geolocation, which is recognized by the browser as part of the Geolocation API and which returns a truevalue if geolocation is supported.

Here is the getLocation() function:

function getLocation() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showLocation);
}
}

· The showLocation() function: When the browser supports geolocation, the next step is to call the showlocation function, which calculates and displays the user’s location.

And here is the showLocation() function:

function showLocation(position){
// 2. Hardcode your store location on line 12 and 13, and update the comment to reflect your McDuck's restaurant address
// Nik's apt @ Perry & W 4th St (change to your restaurant location)

var mcduckslat=40.735383;
var mcduckslon=-74.002994;

// current location
var currentpositionlat=position.coords.latitude;
var currentpositionlon=position.coords.longitude;

// calculate the distance between current location and McDuck's location
var distance=getDistanceFromLatLonInMiles(mcduckslat, mcduckslon,currentpositionlat,currentpositionlon);

// Displays the location using .innerHTML property and the lat & long coordinates for your current location
document.getElementById("geodisplay").innerHTML="Latitude: " + currentpositionlat + "<br>Longitude: " + currentpositionlon;

}

// haversine distance formula
The rest omitted for brevity because it's shown in a previous chapter

The showLocation() function performs the following tasks:

· Assigns the McDuck longitude and latitude to mduckslat and mcduckslon (Lines 12 and 13 of the code).

· Assigns the longitude and latitude of the customer’s current location to currentpositionlat and currentpositionlon (Lines 16 and 17 of the code).

· Calculates the distance in miles between those two points and assigns that distance to a variable called distance (Line 20 of the code). The Haversine formula calculates the distance between two points on a sphere, in this case the earth, and the code is shown online but omitted here for brevity.

· After the button is clicked, the getElementByID and .innerHTML methods display the customer’s current longitude and latitude in an HTML tag named "geodisplay" using the id attribute.

remember.eps JavaScript functions are case-sensitive, so getLocation() differs from getlocation(). The letter L is uppercase in the first function, and lowercase in the second function. Similarly, showLocation() differs from showlocation() for the same reason.

Coding steps for you to follow

With some of the code already written, and with research in the previous chapter, follow these steps to insert the code:

1. Insert the HTML button code below with onclick attribute calling the getLocation() function after line 8 in the HTML file.

<button onclick="getLocation()">McDuck's Check-in</button>

After you insert this code, press the button. If your location settings are enabled and you inserted the code properly, you will see a dialog box asking for your permission to share your computer’s location. As shown in Figure 12-2, look at the top of your browser window and click Allow.

9781118951309-fg1202.tif

Figure 12-2: The browser asks for your permission before sharing your location.

2. Update lines 12 and 13 in the JavaScript file with the latitude and longitude of the restaurant near you serving as the McDuck’s store.

After you have updated the location, make sure to change the comment in line 10 to reflect the address of your restaurant (instead of my apartment).

3. Add an alert that displays the distance between your location and the restaurant.

The distance variable stores the miles from your current location to the restaurant. Make a rough estimate — or use a map for greater precision — of your current distance from the restaurant you picked. Then using an alert, show the distance by inserting this code below in line 23.

alert(distance);

If the distance in the alert is larger or smaller than you expected, you likely entered in incorrect values for the latitude or longitude. If the distance matches your estimate, insert two slashes ("//") before the alert and comment it out.

4. Write an if-else statement on line 26 to show an alert if you are within your threshold distance to the restaurant.

My code, based on a half-mile threshold distance, is displayed below — yours may vary depending on your alert text and threshold distance. (See Figure 12-3.)

if (distance < 0.5) {
alert("You get a free burger");
}
else {
alert("Thanks for checking in!");
}

9781118951309-fg1203.tif

Figure 12-3: The McDuck’s app displaying an offer to come to the store.

tip.eps When your app logic is working, you can change alert("You get a free burger"); to an actual picture of a coupon or burger. To do so, replace the entire line the alert is on with the following code:

document.getElementById("effect").innerHTML="<img src='http://www.image.com/image.jpg'>";

Replace the URL after src and within the single quotes to your own image URL. Be sure to keep the double quotation marks after the first equals sign and before the semi-colon, and the single quotation marks after the second equals sign and before the right angle bracket.

5. (Optional) When the app is working, change the text colors and insert background images to make the app look more professional.

Use hex-values or color names, as discussed in Chapter 6, to change the text and background colors. Additionally, you can insert a background image, as you did in the Codecademy About You exercise, using the following code (see Figure 12-4):

background-image: url("http://www.image.com/image.jpg");

9781118951309-fg1204.tif

Figure 12-4: The completed McDuck’s app with styled content displaying an image to the user.

Debugging Your App

When coding your app, you will almost inevitably write code that does not behave as you intended. HTML and CSS are relatively forgiving, with the browser even going so far as to insert tags so the page renders properly. However, JavaScript isn’t so forgiving, and the smallest error, such as a missing quotation mark, can cause the page to not render properly.

Errors in web applications can consist of syntax errors, logic errors, and display errors. Given that we worked through the logic together, the most likely culprit causing errors in your code will be syntax related. Here are some common errors to check when debugging your code:

· Opening and closing tags: In HTML, every opening tag has a closing tag, and you always close the most recently opened tag first.

· Right and left angle brackets: In HTML, every left angle bracket < has a right angle bracket >.

· Right and left curly brackets: In CSS and JavaScript, every left curly bracket must have a right curly bracket. It can be easy to accidentally delete it or forget to include it.

· Indentation: Indent your code and use plenty of tabs and returns to make your code as readable as possible. Proper indentation will make it easier for you to identify missing tags, angle brackets, and curly brackets.

· Misspelled statements: Tags in any language can be misspelled, or spelled correctly but not part of the specification. For example, in HTML, <img scr="image.jpg"> is incorrect because scr should really be src for the image to render properly. Similarly, in CSS font-color looks like it is spelled correctly but no such property exists. The correct property to set font color is just color.

Keep these errors in mind when debugging — they may not solve all your problems, but they should solve many of them. If you have tried the steps above and still cannot debug your code, tweet me at @nikhilgabraham and include the #codingFD hashtag and your Codepen.io URL in your tweet.