Chapter i. Writing Your Showtime JavaScript Programme

Past itself, HTML doesn't have any smarts: It can't do math, it tin can't effigy out if someone has correctly filled out a form, and information technology can't make decisions based on how a web visitor interacts with it. Basically, HTML lets people read text, expect at pictures, sentinel videos, and click links to move to other spider web pages with more than text, pictures, and videos. In order to add intelligence to your web pages then they can respond to your site's visitors, you need JavaScript.

JavaScript lets a web page react intelligently. With it, y'all tin create smart web forms that let visitors know when they've forgotten to include necessary information. You tin make elements appear, disappear, or move around a web page (encounter Figure i-ane). Y'all can even update the contents of a web page with information retrieved from a web server—without having to load a new web page. In short, JavaScript lets you make your websites more engaging, effective, and useful.

Annotation

Really, HTML5 does add some smarts to HTML—including basic form validation. But because not all browsers support these nifty additions (and considering you can do a whole lot more with forms and JavaScript), you still demand JavaScript to build the best, well-nigh user-friendly and interactive forms. You can learn more about HTML5 and spider web forms in Ben Henick's HTML5 Forms (O'Reilly) and Gaurav Gupta'due south Mastering HTML5 Forms (Packt Publishing).

The Interactive Ear (), an interactive guide to human hearing, lets visitors learn about and explore the different parts of the human ear. New information appears in response to mouse movements and clicks. With JavaScript, you can create your own interactive effects.

Effigy 1-ane. The Interactive Ear (http://www.amplifon.co.uk/interactive-ear/), an interactive guide to homo hearing, lets visitors larn about and explore the different parts of the human ear. New data appears in response to mouse movements and clicks. With JavaScript, y'all can create your own interactive effects.

Introducing Programming

For a lot of people, the term "computer programming" conjures up visions of super-intelligent nerds hunched over keyboards, typing well-nigh unintelligible gibberish for hours on end. And, honestly, some programming is similar that. Programming can seem like circuitous magic that'due south well beyond the average mortal. But many programming concepts aren't difficult to grasp, and every bit programming languages go, JavaScript is a expert first linguistic communication for someone new to programming.

Still, JavaScript is more than complex than either HTML or CSS, and programming often is a foreign world to web designers; so one goal of this book is to assistance you lot recollect more than similar a programmer. Throughout this book, you'll learn cardinal programming concepts that apply whether you're writing JavaScript, ActionScript, or fifty-fifty writing a desktop program using C++. More importantly, y'all'll acquire how to approach a programming task so y'all'll know exactly what you lot want to exercise before you starting time calculation JavaScript to a spider web page.

Many web designers are immediately struck past the strange symbols and words used in JavaScript. An average JavaScript programme is sprinkled with symbols ({ } [ ] ; , () !=) and total of unfamiliar words (var, null, else if). In many ways, learning a programming language is a lot similar learning another language. Y'all need to learn new words, new punctuation, and sympathise how to put them together and then you can communicate successfully.

Every programming language has its own prepare of keywords and characters, and its ain set of rules for putting those words and characters together—the linguistic communication'southward syntax . You'll need to memorize the words and rules of the JavaScript linguistic communication (or at least proceed this book handy every bit a reference). When learning to speak a new language, you quickly realize that placing an accent on the wrong syllable can make a discussion unintelligible. Likewise, a unproblematic typo or even a missing punctuation marking tin can preclude a JavaScript program from working, or trigger an error in a web browser. You'll make enough of mistakes as you get-go to learn to program—that's but the nature of programming.

At kickoff, you'll probably find JavaScript programming frustrating—you lot'll spend a lot of your fourth dimension tracking down errors you lot made when typing the script. Besides, you might find some of the concepts related to programming a flake hard to follow at offset. But don't worry: If you've tried to learn JavaScript in the past and gave up because you thought it was as well hard, this book volition aid you lot get past the hurdles that often trip up folks new to programming. (And if you practise accept programming experience, this volume will teach yous JavaScript's idiosyncrasies and the unique concepts involved in programming for web browsers.)

In addition, this book isn't just most JavaScript—it's as well about jQuery, the world's most popular JavaScript library. jQuery makes circuitous JavaScript programming easier… much easier. Then with a piffling bit of JavaScript knowledge and the help of jQuery, you lot'll be creating sophisticated, interactive websites in no time.

What's a Computer Programme?

When you add JavaScript to a web folio, you're writing a computer programme. Granted, most JavaScript programs are much simpler than the programs you apply to read email, retouch photographs, and build web pages. Just even though JavaScript programs (also called scripts ) are simpler and shorter, they share many of the same properties of more than complicated programs.

In a nutshell, any computer program is a series of steps that are completed in a designated order. Say you lot want to display a welcome message using the web-page visitor's name: "Welcome, Bob!" In that location are several things you'd need to practise to attain this task:

  1. Ask the visitor's name .

  2. Get the visitor's response .

  3. Print (that is, display) the message on the spider web page .

While yous may never desire to print a welcome message on a web folio, this example demonstrates the fundamental procedure of programming: Determine what you desire to practise, then break that task down into individual steps. Every time you want to create a JavaScript program, you must go through the procedure of determining the steps needed to achieve your goal. Once you know the steps, yous'll translate your ideas into programming code —the words and characters that make the web browser deport how you desire information technology to.

How to Add JavaScript to a Folio

Web browsers are built to empathise HTML and CSS and catechumen those languages into a visual display on the screen. The part of the web browser that understands HTML and CSS is called the layout or rendering engine. Simply about browsers also have something called a JavaScript interpreter . That's the office of the browser that understands JavaScript and can execute the steps of a JavaScript programme. The spider web browser is ordinarily expecting HTML, so you must specifically tell the browser when JavaScript is coming by using the <script> tag.

The <script> tag is regular HTML. It acts similar a switch that in upshot says "Hey, web browser, here comes some JavaScript lawmaking; you don't know what to exercise with information technology, so hand it off to the JavaScript interpreter." When the web browser encounters the endmost </script> tag, information technology knows it'south reached the finish of the JavaScript program and can get back to its normal duties.

Much of the time, you'll add together the <script> tag in the spider web page'due south <head> section, like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/ html4/strict.dtd"> <html> <head> <title>My Web Page</title>                              <script type="text/javascript">                                            </script>                            </head>

The <script> tag's type aspect indicates the format and the type of script that follows. In this case, blazon="text/javascript" means the script is regular text (just like HTML) and that it'south written in JavaScript.

If you're using HTML5, life is even simpler. You can skip the type attribute entirely:

<!doctype html> <html> <head> <meta charset="UTF-8"> <championship>My Web Folio</title>                              <script>                                            </script>                            </head>

In fact, web browsers let you leave out the type aspect in HTML 4.01 and XHTML 1.0 files as well—the script will run the aforementioned; however, your page won't validate correctly without the blazon aspect (run across the box on Validating Web Pages for more on validation). This book uses HTML5 for the doctype, only the JavaScript code will be the aforementioned and work the same for HTML iv.01, and XHTML 1.

You then add your JavaScript code betwixt the opening and endmost <script> tags:

<!doctype html> <html> <head> <meta charset="UTF-eight"> <title>My Web Page</title> <script>                              alarm('hello earth!');                            </script> </head>

You'll notice out what this JavaScript does in a moment. For now, turn your attending to the opening and closing <script> tags. To add a script to your page, showtime past inserting these tags. In many cases, yous'll put the <script> tags in the page'southward <caput> in order to keep your JavaScript lawmaking neatly organized in ane expanse of the web folio.

However, it'due south perfectly valid to put <script> tags anywhere within the page's HTML. In fact, as you'll run across later in this chapter, there'south a JavaScript command that lets you write information direct into a web folio. Using that command, you place the <script> tags in the location on the page (somewhere inside the body) where you want the script to write its bulletin. In fact, it'southward mutual to put <script> tags but beneath the closing </body> tag—this approach makes sure the page is loaded and the company sees it before running any JavaScript.

External JavaScript Files

Using the <script> tag as discussed in the previous section lets you add JavaScript to a single web page. Merely many times you'll create scripts that you lot want to share with all of the pages on your site. For example, you might add a panel of boosted navigation options that slides onto the page in response to a visitor'due south mouse movements (meet Figure 1-2). You'll desire that aforementioned fancy slide-in console on every page of your site, but copying and pasting the same JavaScript code into each page is a really bad idea for several reasons.

Starting time, it'southward a lot of work copying and pasting the same code over and once again, especially if you have a site with hundreds of pages. Second, if you ever decide to modify or enhance the JavaScript lawmaking, you'll need to locate every page using that JavaScript and update the code. Finally, considering all of the lawmaking for the JavaScript program would be located in every spider web page, each page will be that much larger and slower to download.

A improve approach is to use an external JavaScript file. If yous've used external CSS files for your web pages, this technique should experience familiar. An external JavaScript file is a text file containing JavaScript code and ending with the file extension .js navigation.js , for instance. The file is linked to a spider web page using the <script> tag. For example, to add this JavaScript file to your abode page, y'all might write the following:

<!doctype html> <html> <head> <meta charset="UTF-8"> <title>My Spider web Folio</title> <script                                  src="navigation.js"                ></script> </head>

The src aspect of the <script> tag works just like the src aspect of an <img> tag, or an <a> tag's href attribute. In other words, it points to a file either in your website or on another website (run across the box on URL Types).

Note

When adding the src attribute to link to an external JavaScript file, don't add together any JavaScript code between the opening and closing <script> tags. If you desire to link to an external JavaScript file and add custom JavaScript code to a page, use a second set of <script> tags. For example:

<script src="navigation.js"></script> <script>   alarm('Hello earth!'); </script>

You can (and often will) attach multiple external JavaScript files to a single web page. For example, you might take created one external JavaScript file that controls a drop-down navigation panel, and some other that lets y'all add a nifty slideshow to a page of photos. On your photo gallery page, you'd desire to take both JavaScript programs, and so you'd attach both files.

In addition, y'all can attach external JavaScript files and add a JavaScript programme to the same page similar this:

<!doctype html> <html> <head> <meta charset="UTF-8"> <title>My Web Folio</title>                                  <script src="navigation.js"></script>                                                  <script src="slideshow.js"></script>                                                  <script>                                                  alert('howdy world!');                                                  </script>                                </caput>

Nike.com's website uses JavaScript extensively to create a compelling showcase for their products. The home page (top) includes a row of navigation buttons along the top—Men, Women, Kids, and so on—that, when moused over, reveal a panel of additional navigation options. For example, mousing over the Sports button (circled in bottom image) reveals a panel listing different sports that Nike makes products for.

Figure 1-ii. Nike.com's website uses JavaScript extensively to create a compelling showcase for their products. The home page (peak) includes a row of navigation buttons along the summit—Men, Women, Kids, and then on—that, when moused over, reveal a panel of additional navigation options. For example, mousing over the Sports push (circled in bottom epitome) reveals a panel list unlike sports that Nike makes products for.

Just remember that you must use one set up of opening and closing <script> tags for each external JavaScript file. You lot'll create an external JavaScript file in the tutorial that starts on Attaching an External JavaScript File.

You can keep external JavaScript files anywhere within your website's root folder (or any subfolder inside the root). Many web developers create a special directory for external JavaScript files in the site'southward root binder: common names are js (meaning JavaScript) or libs (meaning libraries).

Note

Sometimes the order in which you adhere external JavaScript files matters. As y'all'll run across after in this book, sometimes scripts you write depend upon code that comes from an external file. That's often the instance when using JavaScript libraries (JavaScript code that simplifies circuitous programming tasks). You'll meet an example of a JavaScript library in action in the tutorial on Attaching an External JavaScript File.

Your First JavaScript Programme

The best mode to learn JavaScript programming is by actually programming. Throughout this book, y'all'll find hands-on tutorials that have you step past step through the process of creating JavaScript programs. To get started, yous'll need a text editor (see Software for JavaScript Programming for recommendations), a spider web browser, and the exercise files located at https://github.com/sawmac/js3e (come across the following Note for consummate instructions).

Notation

The tutorials in this chapter require the example files from this book'south website, www.missingmanuals.com/cds/jsjq3emm. (The tutorial files are stored every bit a single Zip file.)

In Windows, download the Nix file and double-click it to open the archive. Click the Excerpt All Files option, and then follow the instructions of the Extraction Magician to unzip the files and place them on your figurer. If you take trouble opening the Zip file, the free 7-Zero utility can aid: www.seven-zip.org.

On a Mac, only double-click the file to decompress information technology. After you've downloaded and decompressed the files, you should take a folder named MM_JAVASCRIPT3E on your computer, containing all of the tutorial files for this volume.

To become your feet wet and provide a gentle introduction to JavaScript, your start program volition exist very simple:

  1. In your favorite text editor, open the file hello.html .

    This file is located in the chapter01 binder in the MM_JAVASCRIPT3E folder you downloaded as described in the note above. Information technology's a very uncomplicated HTML page, with an external cascading style canvas to add a little visual excitement.

  2. Click in the empty line but before the closing </head> tag and type :

    <script>

    This code is actually HTML, non JavaScript. It informs the spider web browser that the stuff following this tag is JavaScript.

  3. Press the Return primal to create a new blank line, and type :

    warning('hello globe');

    You've just typed your first line of JavaScript code. The JavaScript alert() role is a command that pops open up an Alert box and displays the message that appears inside the parentheses—in this instance, hello world . Don't worry about all of the punctuation (the parentheses, quotes, and semicolon) only yet. You'll learn what they practise in the next affiliate.

  4. Press the Return primal once more, and type </script> . The code should now look like this :

    <link href="../_css/site.css" rel="stylesheet">                                          <script>                                                              alert('howdy world');                                                              </script>                                        </head>

    In this example, the stuff y'all just typed is shown in boldface. The 2 HTML tags are already in the file; make sure you blazon the lawmaking exactly where shown.

  5. Launch a web browser and open up the hi.html file to preview it .

    A JavaScript Alert box appears (see Figure 1-three). Notice that the page is blank when the alert appears. (If you don't see the Alarm box, you probably mistyped the code listed in the previous steps. Double-check your typing and read the following Tip.)

    Tip

    When you lot starting time start programming, y'all'll be shocked at how ofttimes your JavaScript programs don't seem to work…at all. For new programmers, the most common crusade of nonfunctioning programs is unproblematic typing mistakes. Ever double-check to make sure you spelled commands (like alert in the start script) correctly. Also, detect that punctuation frequently comes in pairs (the opening and closing parentheses, and single-quote marks from your first script, for instance). Make sure y'all include both opening and closing punctuation marks when they're required.

  6. Click the Alert box's OK button to close information technology .

    When the Alarm box disappears, the web page appears in the browser window.

    Although this first program isn't world-shatteringly complex (or even that interesting), it does demonstrate an important concept: A web browser will run a JavaScript program the moment it reads in the JavaScript lawmaking. In this example, the alert() command appeared earlier the web browser displayed the web page, because the JavaScript code appeared before the HTML in the <body> tag. This concept comes into play when you first writing programs that manipulate the HTML of the web folio—every bit you'll learn in Chapter iii.

The JavaScript Alert box is a quick way to grab someone's attention. It's one of the simplest JavaScript commands to learn and use.

Effigy one-iii. The JavaScript Alert box is a quick way to grab someone's attention. It's ane of the simplest JavaScript commands to learn and use.

Note

Some versions of Internet Explorer (IE) don't like to run JavaScript programs in spider web pages that you lot open up directly off your hard drive, for fright that the code might practise something harmful. And so when you try to preview the tutorial files for this book in Internet Explorer, you might see a message saying that IE has blocked the script. Click "Allow blocked content."

This annoying behavior merely applies to spider web pages you preview from your calculator, not to files yous put up on a web server. To avert hit the "Permit blocked content" button over and over, preview pages in a different web browser, like Chrome or Firefox.

Writing Text on a Spider web Folio

The script in the previous section popped upwardly a dialog box in the heart of your monitor. What if yous want to print a message directly onto a web page using JavaScript? There are many means to do then, and y'all'll learn some sophisticated techniques later in this book. However, you lot can attain this simple goal with a built-in JavaScript control, and that's what you'll do in your second script:

  1. In your text editor, open the file hello2.html .

    While <script> tags usually appear in a web page's <head>, you tin put them and JavaScript programs direct in the page'due south trunk.

  2. Directly below <h1>Writing to the document window</h1> , type the post-obit lawmaking :

    <script> certificate.write('<p>Hello globe!</p>'); </script>

    Similar the alert() role, certificate.write() is a JavaScript control that literally writes out whatever you lot identify between the opening and closing parentheses. In this case, the HTML <p>Howdy world!</p> is added to the page: a paragraph tag and ii words.

  3. Salve the folio and open up it in a web browser .

    The page opens and the words "Hullo globe!" appear below the headline (run into Effigy 1-4).

Note

The tutorial files you downloaded too include the completed version of each tutorial. If you can't seem to get your JavaScript working, compare your work with the file that begins with complete_ in the aforementioned binder as the tutorial file. For example, the file complete_hello2.html contains a working version of the script yous added to file hello2.html.

The ii scripts yous just created may exit you feeling a fiddling underwhelmed with JavaScript…or this book. Don't worry—this is only the offset. It'southward important to get-go out with a total understanding of the basics. You lot'll be doing some very useful and complicated things using JavaScript in just a few chapters. In fact, in the remainder of this affiliate you'll become a taste of some of the avant-garde features you'll be able to add to your web pages after y'all've worked your way through the start two parts of this volume.

Attaching an External JavaScript File

As discussed on External JavaScript Files, you lot'll unremarkably put JavaScript code in a divide file if you desire to use the same scripts on more one web folio. Yous then instruct your web pages to load that file and employ the JavaScript inside it. External JavaScript files also come in handy when you're using someone else's JavaScript code. In particular, there are collections of JavaScript code called libraries , which provide useful JavaScript programming. Usually, these libraries make it piece of cake to do something that'due south normally quite hard. Yous'll learn more than about JavaScript libraries on Almost JavaScript Libraries, and, in detail, the JavaScript library this book (and much of the Web) uses—jQuery.

Wow. This script may not be something to

Figure 1-four. Wow. This script may not be something to "document.write" home almost—ha, ha, JavaScript humour—only it does demonstrate that y'all can utilise JavaScript to add content to a spider web page, a trick that comes in handy when you desire to display messages (like "Welcome back to the site, Dave") after a web folio has downloaded.

Only for now, you'll become experience attaching an external JavaScript file to a folio, and writing a short program that does something absurd:

  1. In your text editor, open up the file fadeIn.html .

    This folio contains simply some elementary HTML—a few <div> tags, a headline, and a couple of paragraphs. You'll exist calculation a elementary visual outcome to the folio, which causes all of the content to slowly fade into view.

  2. Click in the bare line between the <link> and endmost </head> tags near the top of the folio, and blazon :

    <script src="../_js/jquery.min.js"></script>

    This code links a file named jquery.min.js , which is independent in a folder named _js , to this web page. When a web browser loads this web page, information technology also downloads the jquery.min.js JavaScript file and runs the code inside it.

    Next, you'll add your own JavaScript programming to this folio.

    Notation

    The min part means that the file is minimized —a procedure that removes unneeded whitespace and condenses the code to make the file smaller and so that it downloads faster.

  3. Printing Return to create a new bare line, and then type :

    <script>

    HTML tags commonly travel in pairs—an opening and closing tag. To make sure you lot don't forget to close a tag, it helps to shut the tag immediately later typing the opening tag, and so fill in the stuff that goes between the tags.

  4. Press Return twice to create 2 blank lines, and then type :

    </script>

    This ends the cake of JavaScript code. At present you'll add some programming.

  5. Click the empty line between the opening and closing script tags and type :

    $(document).ready(function() {

    Yous're probably wondering what the heck that is. You'll find out all the details of this code on Adding jQuery to a Page, but in a nutshell, this line takes advantage of the programming that's inside the jquery.min.js file to make sure that the browser executes the next line of code at the right time.

  6. Hitting return to create a new line, and so type :

    $('header').hibernate().slideDown(3000);

    This line does something magical: It makes the "JavaScript & jQuery The Missing Manual" header offset disappear and and so slowly slide down onto the page over the course of three seconds (or iii,000 milliseconds). How does information technology practise that? Well, that's part of the magic of jQuery, which makes complex furnishings possible with just a unmarried line of lawmaking.

  7. Hit Return i final time, so type :

    });

    This code closes upwardly the JavaScript code, much as a closing </script> tag indicates the end of a JavaScript programme. Don't worry as well much about all those weird punctuation marks—yous'll learn how they work in detail afterwards in the volume. The main thing you need to make certain of is to type the lawmaking exactly as information technology'southward listed here. One typo, and the program may not work.

    The final code you added to the page should look like the bolded text in the post-obit:

    <link href="../_css/site.css" rel="stylesheet">                                          <script src="../_js/jquery.min.js"></script>                                                              <script>                                                              $(certificate).prepare(part() {                                                              $('header').hide().slideDown(3000);                                                              });                                                              </script>                                        </head>

    Tip

    To brand your programming easier to read, it'south a skilful thought to indent code. Much as you indent HTML tags to show which tags are nested inside of other tags, you lot can indent lines of code that are inside another block of code. For example, the line of code you lot added in step half-dozen is nested inside the code for steps 5 and vii, so hitting Tab or pressing the spacebar a couple of times before typing the code for stride 6 can make your lawmaking easier to understand (every bit pictured in the final lawmaking listed at the end of step 7).

  8. Save the HTML file, and open it in a spider web browser .

    You lot should see the headline—Sliding Down—plus a paragraph and the footer at the bottom of the browser window, followed by the boxes containing "JavaScript & jQuery: The Missing Transmission" slowly slide downward into place. Change the number 3000 to dissimilar values (like 250 and 10000) to see how that changes the way the folio works.

Note

If you attempt to preview this folio in Internet Explorer and it doesn't seem to do annihilation, you lot'll need to click the "Enable blocked content" box that appears at the lesser of the page (see the Note on Note).

Equally you can see, it doesn't take a whole lot of JavaScript to do some amazing things to your web pages. Thank you to jQuery, you'll be able to create sophisticated, interactive websites even if you're non a programming wizard. However, y'all'll notice it helps to know the nuts of JavaScript and programming. Capacity Chapter 2 and Chapter 3 will cover the basics of JavaScript to get you lot comfy with the fundamental concepts and syntax that brand up the language.

Tracking Down Errors

The most frustrating moment in JavaScript programming comes when y'all effort to view your JavaScript-powered folio in a spider web browser…and nothing happens. It'southward one of the most common experiences for programmers. Even experienced programmers ofttimes don't become it right the first time they write a program, then figuring out what went wrong is just office of the game.

Virtually web browsers are prepare to silently ignore JavaScript errors, then you lot usually won't even run across a "Hey, this programme doesn't piece of work!" dialog box. (Generally, that's a proficient matter, as you don't desire a JavaScript fault to interrupt the feel of viewing your web pages.)

So how exercise you lot figure out what'southward gone incorrect? In that location are many ways to track errors in a JavaScript programme. You'll larn some advanced debugging techniques in Affiliate 17, but the nigh basic method is to consult the spider web browser. Virtually web browsers keep runway of JavaScript errors and tape them in a separate window chosen an error panel . When you load a web page that contains an error, yous can and so view the panel to go helpful data about the error, like which line of the web page information technology occurred in and a description of the error.

Often, y'all can notice the respond to the problem in the error console, fix the JavaScript, and then the page will piece of work. The console helps y'all weed out the basic typos you make when you lot first start programming, similar forgetting endmost punctuation, or mistyping the name of a JavaScript control. Yous can use the error console in your favorite browser, but because scripts sometimes piece of work in one browser and not another, this department shows yous how to plough on the JavaScript console in all major browsers, and then you can track down problems in each.

The Chrome JavaScript Console

Google's Chrome browser is beloved by many a spider web developer. Its DevTools characteristic gives you many ways to troubleshoot HTML, CSS, and JavaScript problems. Also, its JavaScript console is a peachy place to begin tracking down errors in your code. It not only describes the errors information technology finds, it besides identifies the line in your code where each error occurred.

To open up the JavaScript panel, click the Customize bill of fare button (circled in Figure 1-v) and choose Tools→JavaScript Console. Or use the keyboard shortcut Ctrl+Shift+J (Windows) or ⌘-Option-J (Mac).

Click the Customize menu (circled) to access the JavaScript console as well as other helpful tools. Choosing the Developer Tools option is another way to get to the console, as the JavaScript console is part of a larger set of Chrome tools called the Developer Tools (DevTools for short). You'll learn more about those tools in Chapter 17.

Figure 1-5. Click the Customize menu (circled) to access the JavaScript console every bit well equally other helpful tools. Choosing the Developer Tools selection is some other fashion to get to the console, every bit the JavaScript console is part of a larger gear up of Chrome tools called the Developer Tools (DevTools for short). You'll learn more almost those tools in Chapter 17.

After you open the console, you can examine whatever errors that appear in the electric current page. For example, in Figure 1-six, the console identifies the fault equally an "Uncaught SyntaxError: Unexpected token ILLEGAL." OK, it may not be immediately obvious what that means, but as you come across (and fix) more errors yous'll become used to these terse descriptions. Basically, a syntax error points to some kind of typographical error—an error with the syntax or language of the program. The "Unexpected token ILLEGAL" role just means that the browser has encountered an illegal character, or (and here'southward the tricky part) that at that place'due south a missing graphic symbol. In this case, looking closely at the lawmaking you tin run across there'due south an opening single quote mark earlier "tiresome" but no final quote mark.

The console also identifies the name of the file the fault is in ( complete_slide.html , in this instance) and the line number the fault occurs (line 10). Click the filename, and Chrome opens the file in a higher place the console and briefly highlights the line (run across Figure 1-5).

Tip

Because the error console displays the line number where the error occurred, yous may want to use a text editor that can show line numbers. That way, y'all tin can easily jump from the mistake console to your text editor and identify the line of lawmaking you lot need to fix.

Chrome's JavaScript console identifies errors in your programs. Click the filename listed to the right of the error, and Chrome briefly highlights the page with the error (circled).

Figure one-half-dozen. Chrome's JavaScript console identifies errors in your programs. Click the filename listed to the correct of the error, and Chrome briefly highlights the folio with the error (circled).

Unfortunately, there'south a long listing of things that tin go wrong in a script, from simple typos to complex errors in logic. When yous're merely starting out with JavaScript programming, many of your errors will be the unproblematic typographic sort. For example, you might forget a semicolon, quote mark, or parenthesis, or misspell a JavaScript command. Y'all're especially prone to typos when following examples from a volume (similar this i). Here are a few common mistakes y'all might make and the (not-then obvious) error messages you may come across:

  • Missing punctuation . As mentioned earlier, JavaScript programming oft involves lots of symbol pairs similar opening and closing parentheses and brackets. For example, if you type warning('hi';—leaving off the endmost parenthesis—y'all'll probably get the: "Unexpected token;" message, pregnant that Chrome was expecting something other than the character it's showing. In this case, it encountered the semicolon instead of the closing parenthesis.

  • Missing quote marks . A string is a series of characters enclosed past quote marks (yous'll larn almost these in greater detail on Types of Data). For example, 'howdy' is a string in the lawmaking alert('hellO');. It'south easy to forget either the opening or closing quote mark. It's also easy to mix up those quote marks; for instance, by pairing a unmarried-quote with a double quote similar this: alert('hello");. In either instance, yous'll probably see an "Uncaught SyntaxError: Unexpected token ILLEGAL" error.

  • Misspelling commands . If you misspell a JavaScript command—aler('hellO');—you lot'll get an fault saying that the misspelled command isn't defined: for example, "Uncaught ReferenceError: aler is not defined," if you misspell the alert control. You'll also encounter problems when y'all misspell jQuery functions (like the .hide() and .slideDown() functions in the previous tutorial). In this case, y'all'll get a different mistake. For example, if yous mistyped "hide" as "hid" in step 6 on Attaching an External JavaScript File, Chrome will give you this error: "Uncaught TypeError: Object [object Object] has no method 'hid'".

  • Syntax error . Occasionally, Chrome has no idea what you were trying to practise and provides this generic error message. A syntax error represents some mistake in your code. It may not exist a typo, but yous may have put together one or more statements of JavaScript in a way that isn't allowed. In this case, you need to look closely at the line where the error was found and try to figure out what mistake y'all fabricated. Unfortunately, these types of errors often crave experience with and understanding of the JavaScript language to set.

As y'all can see from the preceding list, many errors yous'll make only involve forgetting to type one of a pair of punctuation marks—like quote marks or parentheses. Fortunately, these are easy to fix, and every bit you get more experience programming, yous'll eventually stop making them near completely (no programmer is perfect).

The Internet Explorer Console

Internet Explorer provides a sophisticated set of developer tools for not only viewing JavaScript errors, but also analyzing CSS, HTML, and transfers of information over the network. When open, the developer tool window appears in the lesser one-half of the browser window. Printing the F12 cardinal to open the developer tools, and press it again to close them. You'll find JavaScript errors listed under the Console tab (circled in Figure 1-7).

Annotation

If y'all first open a spider web page and then open up the Internet Explorer console, you won't run into any errors (fifty-fifty if there are some). You lot demand to reload the folio to see any errors. Once the panel is open, you'll encounter errors on the pages yous visit as they load.

IE's Console displays fault messages similar to those described earlier for Chrome. Even so, sometimes they're very dissimilar. For example, IE's "Unterminated cord constant" is an "Unexpected token ILLEGAL" error in Chrome. Similar Chrome, Internet Explorer identifies the line of code in the HTML file where the mistake occurred, which y'all can click to see the actual code where the mistake occurs.

The Internet Explorer developer tools provide access to JavaScript errors that occur on a page, as well as a whole lot of other information.

Figure ane-7. The Internet Explorer developer tools provide access to JavaScript errors that occur on a page, also as a whole lot of other information.

The Firefox JavaScript Web Console

Mozilla's Firefox browser also gives you lot a console to view JavaScript errors. To open the JavaScript console, on Windows click the Firefox tab in the superlative left of the browser window and choose Spider web Developer→Web Panel. On a Mac, select Tools→Web Developer→Web Console. Or utilise the keyboard shortcuts Ctrl+Shift+I (Windows) or ⌘-Pick-Thousand (Mac).

Once the console opens, you'll come across whatsoever JavaScript errors on the folio. Unfortunately, Firefox's Web Console is more like a fire hose of data than a simple JavaScript mistake reporter (Figure 1-viii). That'southward because it provides information on all sorts of things: files downloaded, CSS and HTML errors, and more.

Note

The Firebug plug-in (http://getfirebug.com) greatly expands on Firefox'south Mistake Console. In fact, it provided the model for the programmer tools in Net Explorer, Chrome, and Safari (discussed next).

If you don't want to see all of the messages in Firefox's Web Console, just click the button for the type of message you wish to hide. For example, click the CSS button to hide CSS error messages, the Security button to hide security warnings, and so on. You'll know if the button is disabled because it looks lighter gray, like the CSS and Security buttons here. A button is enabled when it's darker and looks like it has been pressed

Figure i-8. If you lot don't want to see all of the messages in Firefox'due south Web Console, merely click the button for the type of message you wish to hibernate. For example, click the CSS push button to hibernate CSS fault messages, the Security button to hide security warnings, and then on. Y'all'll know if the button is disabled because it looks lighter gray, like the CSS and Security buttons hither. A button is enabled when it'due south darker and looks like it has been pressed "in," like the Net, JS (short for JavaScript), and Logging buttons hither.

The Safari Error Console

Safari's error console is bachelor from the Develop card: Develop→Prove Fault Panel (or, if you're on a Mac, utilize the Pick-⌘-C keyboard shortcut). Notwithstanding, the Develop card isn't normally turned on when Safari is installed, then there are a couple of steps to become to the JavaScript console.

To plow on the Develop menu, you need to start access the Preferences window. Choose Safari→Preferences. Once the Preferences window opens, click the Advanced push button. Turn on the "Evidence Develop card in carte du jour bar" box and close the Preferences window.

When you restart Safari, the Develop menu will appear betwixt the Bookmarks and Window menus in the card bar at the top of the screen. Select Develop→Testify Mistake Panel to open up the console (see Figure i-9).

The Safari Error Console displays the name of the JavaScript error, the filename (and location), and the line on which Safari encountered the error. Each tab or browser window has its own error console, so if you've already opened the console for one tab, you need to choose Develop→Show Error Console again if you wish to see an error for another tab or window. In addition, if you reload a page, Safari doesn't clear any prior errors on that page, so you can end up with a long list of old, fixed errors as you work on a page and reload it. The answer: click the Trash icon (circled) to remove the list of old errors, and then reload the page.

Figure 1-9. The Safari Fault Console displays the proper name of the JavaScript error, the filename (and location), and the line on which Safari encountered the mistake. Each tab or browser window has its own error panel, so if you've already opened the console for ane tab, you need to choose Develop→Bear witness Error Console once again if yous wish to run across an fault for another tab or window. In add-on, if you lot reload a page, Safari doesn't clear any prior errors on that folio, so you tin finish up with a long list of former, fixed errors equally you piece of work on a page and reload it. The reply: click the Trash icon (circled) to remove the listing of onetime errors, and so reload the page.

Note

If you lot're on Windows, you may take an old version of the Safari browser. Apple has stopped updating Safari for Windows, so the Safari information shown here may not apply to you.

Get JavaScript & jQuery: The Missing Manual, third Edition now with the O'Reilly learning platform.

O'Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.