By itself, HTML doesnât have any smarts: It canât do math, it canât figure out if someone has correctly filled out a form, and it canât make decisions based on how a web visitor interacts with it. Basically, HTML lets people read text, look at pictures, watch videos, and click links to move to other web pages with more text, pictures, and videos. In order to add intelligence to your web pages so they can respond to your siteâs visitors, you need JavaScript.
JavaScript lets a web page react intelligently. With it, you can create smart web forms that let visitors know when theyâve forgotten to include necessary information. You can make elements appear, disappear, or move around a web page (see Figure 1-1). You 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.
Note
Actually, HTML5 does add some smarts to HTMLâincluding basic form validation. But because not all browsers support these nifty additions (and because you can do a whole lot more with forms and JavaScript), you still need JavaScript to build the best, most user-friendly and interactive forms. You can learn more about HTML5 and web forms in Ben Henickâs HTML5 Forms (OâReilly) and Gaurav Guptaâs Mastering HTML5 Forms (Packt Publishing).
Figure 1-1. The Interactive Ear (http://www.amplifon.co.uk/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.
For a lot of people, the term âcomputer programmingâ conjures up visions of super-intelligent nerds hunched over keyboards, typing nearly unintelligible gibberish for hours on end. And, honestly, some programming is like that. Programming can seem like complex magic thatâs well beyond the average mortal. But many programming concepts arenât difficult to grasp, and as programming languages go, JavaScript is a good first language for someone new to programming.
Still, JavaScript is more complex than either HTML or CSS, and programming often is a foreign world to web designers; so one goal of this book is to help you think more like a programmer. Throughout this book, youâll learn fundamental programming concepts that apply whether youâre writing JavaScript, ActionScript, or even writing a desktop program using C++. More importantly, youâll learn how to approach a programming task so youâll know exactly what you want to do before you start adding JavaScript to a web page.
Many web designers are immediately struck by the strange symbols and words used in JavaScript. An average JavaScript program is sprinkled with symbols ({ } [ ] ; , () !=) and full of unfamiliar words (var
, null
, else if
). In many ways, learning a programming language is a lot like learning another language. You need to learn new words, new punctuation, and understand how to put them together so you can communicate successfully.
Every programming language has its own set of keywords and characters, and its own set of rules for putting those words and characters togetherâthe languageâs syntax. Youâll need to memorize the words and rules of the JavaScript language (or at least keep this book handy as a reference). When learning to speak a new language, you quickly realize that placing an accent on the wrong syllable can make a word unintelligible. Likewise, a simple typo or even a missing punctuation mark can prevent a JavaScript program from working, or trigger an error in a web browser. Youâll make plenty of mistakes as you start to learn to programâthatâs just the nature of programming.
At first, youâll probably find JavaScript programming frustratingâyouâll spend a lot of your time tracking down errors you made when typing the script. Also, you might find some of the concepts related to programming a bit hard to follow at first. But donât worry: If youâve tried to learn JavaScript in the past and gave up because you thought it was too hard, this book will help you get past the hurdles that often trip up folks new to programming. (And if you do have programming experience, this book will teach you JavaScriptâs idiosyncrasies and the unique concepts involved in programming for web browsers.)
In addition, this book isnât just about JavaScriptâitâs also about jQuery, the worldâs most popular JavaScript library. jQuery makes complex JavaScript programming easierâ¦much easier. So with a little bit of JavaScript knowledge and the help of jQuery, youâll be creating sophisticated, interactive websites in no time.
When you add JavaScript to a web page, youâre writing a computer program. Granted, most JavaScript programs are much simpler than the programs you use to read email, retouch photographs, and build web pages. But even though JavaScript programs (also called scripts) are simpler and shorter, they share many of the same properties of more complicated programs.
In a nutshell, any computer program is a series of steps that are completed in a designated order. Say you want to display a welcome message using the web-page visitorâs name: âWelcome, Bob!â There are several things youâd need to do to accomplish this task:
Ask the visitorâs name.
Get the visitorâs response.
Print (that is, display) the message on the web page.
While you may never want to print a welcome message on a web page, this example demonstrates the fundamental process of programming: Determine what you want to do, then break that task down into individual steps. Every time you want to create a JavaScript program, you must go through the process of determining the steps needed to achieve your goal. Once you know the steps, youâll translate your ideas into programming codeâthe words and characters that make the web browser behave how you want it to.
Web browsers are built to understand HTML and CSS and convert 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. But most browsers also have something called a JavaScript interpreter. Thatâs the part of the browser that understands JavaScript and can execute the steps of a JavaScript program. The web browser is usually 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 like a switch that in effect says âHey, web browser, here comes some JavaScript code; you donât know what to do with it, so hand it off to the JavaScript interpreter.â When the web browser encounters the closing </script>
tag, it knows itâs reached the end of the JavaScript program and can get back to its normal duties.
Much of the time, youâll add the <script>
tag in the web pageâs <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
attribute indicates the format and the type of script that follows. In this case, type=âtext/javascriptâ
means the script is regular text (just like HTML) and that itâs 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"> <title>My Web Page</title><script>
</script>
</head>
In fact, web browsers let you leave out the type attribute in HTML 4.01 and XHTML 1.0 files as wellâthe script will run the same; however, your page wonât validate correctly without the type attribute (see the box on Validating Web Pages for more on validation). This book uses HTML5 for the doctype, but the JavaScript code will be the same and work the same for HTML 4.01, and XHTML 1.
You then add your JavaScript code between the opening and closing <script>
tags:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
alert('hello world!');
</script>
</head>
Youâll find out what this JavaScript does in a moment. For now, turn your attention to the opening and closing <script>
tags. To add a script to your page, start by inserting these tags. In many cases, youâll put the <script>
tags in the pageâs <head>
in order to keep your JavaScript code neatly organized in one area of the web page.
However, itâs perfectly valid to put <script>
tags anywhere inside the pageâs HTML. In fact, as youâll see later in this chapter, thereâs a JavaScript command that lets you write information directly into a web page. 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 message. In fact, itâs common to put <script>
tags just below the closing </body>
tagâthis approach makes sure the page is loaded and the visitor sees it before running any JavaScript.
Using the <script>
tag as discussed in the previous section lets you add JavaScript to a single web page. But many times youâll create scripts that you want to share with all of the pages on your site. For example, you might add a panel of additional navigation options that slides onto the page in response to a visitorâs mouse movements (see Figure 1-2). Youâll want that same fancy slide-in panel 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.
First, itâs a lot of work copying and pasting the same code over and over again, especially if you have a site with hundreds of pages. Second, if you ever decide to change or enhance the JavaScript code, youâll need to locate every page using that JavaScript and update the code. Finally, because all of the code for the JavaScript program would be located in every web page, each page will be that much larger and slower to download.
A better approach is to use an external JavaScript file. If youâve used external CSS files for your web pages, this technique should feel familiar. An external JavaScript file is a text file containing JavaScript code and ending with the file extension .jsânavigation.js, for example. The file is linked to a web page using the <script>
tag. For example, to add this JavaScript file to your home page, you might write the following:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script src="navigation.js"
></script>
</head>
The src
attribute of the <script>
tag works just like the src
attribute 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 (see the box on URL Types).
Note
When adding the src
attribute to link to an external JavaScript file, donât add any JavaScript code between the opening and closing <script>
tags. If you want 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> alert('Hello world!'); </script>
You can (and often will) attach multiple external JavaScript files to a single web page. For example, you might have created one external JavaScript file that controls a drop-down navigation panel, and another that lets you add a nifty slideshow to a page of photos. On your photo gallery page, youâd want to have both JavaScript programs, so youâd attach both files.
In addition, you can attach external JavaScript files and add a JavaScript program to the same page like this:
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>My Web Page</title><script src="navigation.js"></script>
<script src="slideshow.js"></script>
<script>
alert('hello world!');
</script>
</head>
Figure 1-2. 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.
Just remember that you must use one set of opening and closing <script>
tags for each external JavaScript file. Youâll create an external JavaScript file in the tutorial that starts on Attaching an External JavaScript File.
You can keep external JavaScript files anywhere inside 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âs root folder: common names are js (meaning JavaScript) or libs (meaning libraries).
Note
Sometimes the order in which you attach external JavaScript files matters. As youâll see later in this book, sometimes scripts you write depend upon code that comes from an external file. Thatâs often the case when using JavaScript libraries (JavaScript code that simplifies complex programming tasks). Youâll see an example of a JavaScript library in action in the tutorial on Attaching an External JavaScript File.
The best way to learn JavaScript programming is by actually programming. Throughout this book, youâll find hands-on tutorials that take you step by step through the process of creating JavaScript programs. To get started, youâll need a text editor (see Software for JavaScript Programming for recommendations), a web browser, and the exercise files located at https://github.com/sawmac/js3e (see the following Note for complete instructions).
Note
The tutorials in this chapter require the example files from this bookâs website, www.missingmanuals.com/cds/jsjq3emm. (The tutorial files are stored as a single Zip file.)
In Windows, download the Zip file and double-click it to open the archive. Click the Extract All Files option, and then follow the instructions of the Extraction Wizard to unzip the files and place them on your computer. If you have trouble opening the Zip file, the free 7-Zip utility can help: www.7-zip.org.
On a Mac, simply double-click the file to decompress it. After youâve downloaded and decompressed the files, you should have a folder named MM_JAVASCRIPT3E on your computer, containing all of the tutorial files for this book.
To get your feet wet and provide a gentle introduction to JavaScript, your first program will be very simple:
In your favorite text editor, open the file hello.html.
This file is located in the chapter01 folder in the MM_JAVASCRIPT3E folder you downloaded as described in the note above. Itâs a very simple HTML page, with an external cascading style sheet to add a little visual excitement.
Click in the empty line just before the closing
</head>
tag and type:<script>
This code is actually HTML, not JavaScript. It informs the web browser that the stuff following this tag is JavaScript.
Press the Return key to create a new blank line, and type:
alert('hello world');
Youâve just typed your first line of JavaScript code. The JavaScript
alert()
function is a command that pops open an Alert box and displays the message that appears inside the parenthesesâin this case, hello world. Donât worry about all of the punctuation (the parentheses, quotes, and semicolon) just yet. Youâll learn what they do in the next chapter.Press the Return key once more, and type
</script>
. The code should now look like this:<link href="../_css/site.css" rel="stylesheet">
<script>
alert('hello world');
</script>
</head>In this example, the stuff you just typed is shown in boldface. The two HTML tags are already in the file; make sure you type the code exactly where shown.
Launch a web browser and open the hello.html file to preview it.
A JavaScript Alert box appears (see Figure 1-3). Notice that the page is blank when the alert appears. (If you donât see the Alert box, you probably mistyped the code listed in the previous steps. Double-check your typing and read the following Tip.)
Tip
When you first start programming, youâll be shocked at how often your JavaScript programs donât seem to workâ¦at all. For new programmers, the most common cause of nonfunctioning programs is simple typing mistakes. Always double-check to make sure you spelled commands (like
alert
in the first script) correctly. Also, notice that punctuation frequently comes in pairs (the opening and closing parentheses, and single-quote marks from your first script, for example). Make sure you include both opening and closing punctuation marks when theyâre required.Click the Alert boxâs OK button to close it.
When the Alert box disappears, the web page appears in the browser window.
Although this first program isnât earth-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 code. In this example, the
alert()
command appeared before 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 start writing programs that manipulate the HTML of the web pageâas youâll learn in Chapter 3.
Figure 1-3. 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.
Note
Some versions of Internet Explorer (IE) donât like to run JavaScript programs in web pages that you open directly off your hard drive, for fear that the code might do something harmful. 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 only applies to web pages you preview from your computer, not to files you put up on a web server. To avoid hitting the âAllow blocked contentâ button over and over, preview pages in a different web browser, like Chrome or Firefox.
The script in the previous section popped up a dialog box in the middle of your monitor. What if you want to print a message directly onto a web page using JavaScript? There are many ways to do so, and youâll learn some sophisticated techniques later in this book. However, you can achieve this simple goal with a built-in JavaScript command, and thatâs what youâll do in your second script:
In your text editor, open the file hello2.html.
While
<script>
tags usually appear in a web pageâs<head>
, you can put them and JavaScript programs directly in the pageâs body.Directly below
<h1>Writing to the document window</h1>
, type the following code:<script> document.write('<p>Hello world!</p>'); </script>
Like the
alert()
function,document.write()
is a JavaScript command that literally writes out whatever you place between the opening and closing parentheses. In this case, the HTML<p>Hello world!</p>
is added to the page: a paragraph tag and two words.Save the page and open it in a web browser.
The page opens and the words âHello world!â appear below the headline (see Figure 1-4).
Note
The tutorial files you downloaded also 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 same folder as the tutorial file. For example, the file complete_hello2.html contains a working version of the script you added to file hello2.html.
The two scripts you just created may leave you feeling a little underwhelmed with JavaScriptâ¦or this book. Donât worryâthis is only the beginning. Itâs important to start out with a full understanding of the basics. Youâll be doing some very useful and complicated things using JavaScript in just a few chapters. In fact, in the remainder of this chapter youâll get a taste of some of the advanced features youâll be able to add to your web pages after youâve worked your way through the first two parts of this book.
As discussed on External JavaScript Files, youâll usually put JavaScript code in a separate file if you want to use the same scripts on more than one web page. You then instruct your web pages to load that file and use 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 easy to do something thatâs normally quite difficult. Youâll learn more about JavaScript libraries on About JavaScript Libraries, and, in particular, the JavaScript library this book (and much of the Web) usesâjQuery.
Figure 1-4. Wow. This script may not be something to âdocument.writeâ home aboutâha, ha, JavaScript humorâbut it does demonstrate that you can use JavaScript to add content to a web page, a trick that comes in handy when you want to display messages (like âWelcome back to the site, Daveâ) after a web page has downloaded.
But for now, youâll get experience attaching an external JavaScript file to a page, and writing a short program that does something cool:
In your text editor, open the file fadeIn.html.
This page contains just some simple HTMLâa few
<div>
tags, a headline, and a couple of paragraphs. Youâll be adding a simple visual effect to the page, which causes all of the content to slowly fade into view.Click in the blank line between the
<link>
and closing</head>
tags near the top of the page, and type:<script src="../_js/jquery.min.js"></script>
This code links a file named jquery.min.js, which is contained in a folder named _js, to this web page. When a web browser loads this web page, it also downloads the jquery.min.js JavaScript file and runs the code inside it.
Next, youâll add your own JavaScript programming to this page.
Press Return to create a new blank line, and then type:
<script>
HTML tags usually travel in pairsâan opening and closing tag. To make sure you donât forget to close a tag, it helps to close the tag immediately after typing the opening tag, and then fill in the stuff that goes between the tags.
Press Return twice to create two blank lines, and then type:
</script>
This ends the block of JavaScript code. Now youâll add some programming.
Click the empty line between the opening and closing script tags and type:
$(document).ready(function() {
Youâ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.
Hit return to create a new line, and then type:
$('header').hide().slideDown(3000);
This line does something magical: It makes the âJavaScript & jQuery The Missing Manualâ header first disappear and then slowly slide down onto the page over the course of 3 seconds (or 3,000 milliseconds). How does it do that? Well, thatâs part of the magic of jQuery, which makes complex effects possible with just a single line of code.
Hit Return one last time, and then type:
});
This code closes up the JavaScript code, much as a closing
</script>
tag indicates the end of a JavaScript program. Donât worry too much about all those weird punctuation marksâyouâll learn how they work in detail later in the book. The main thing you need to make sure of is to type the code exactly as itâs 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 following:
<link href="../_css/site.css" rel="stylesheet">
<script src="../_js/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('header').hide().slideDown(3000);
});
</script>
</head>Tip
To make your programming easier to read, itâs a good idea to indent code. Much as you indent HTML tags to show which tags are nested inside of other tags, you can indent lines of code that are inside another block of code. For example, the line of code you added in step 6 is nested inside the code for steps 5 and 7, so hitting Tab or pressing the spacebar a couple of times before typing the code for step 6 can make your code easier to understand (as pictured in the final code listed at the end of step 7).
Save the HTML file, and open it in a web browser.
You 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 Manualâ slowly slide down into place. Change the number 3000 to different values (like 250 and 10000) to see how that changes the way the page works.
Note
If you try to preview this page in Internet Explorer and it doesnât seem to do anything, youâll need to click the âEnable blocked contentâ box that appears at the bottom of the page (see the Note on Note).
As you can see, it doesnât take a whole lot of JavaScript to do some amazing things to your web pages. Thanks to jQuery, youâll be able to create sophisticated, interactive websites even if youâre not a programming wizard. However, youâll find it helps to know the basics of JavaScript and programming. Chapters Chapter 2 and Chapter 3 will cover the basics of JavaScript to get you comfortable with the fundamental concepts and syntax that make up the language.
The most frustrating moment in JavaScript programming comes when you try to view your JavaScript-powered page in a web browserâ¦and nothing happens. Itâs one of the most common experiences for programmers. Even experienced programmers often donât get it right the first time they write a program, so figuring out what went wrong is just part of the game.
Most web browsers are set up to silently ignore JavaScript errors, so you usually wonât even see a âHey, this program doesnât work!â dialog box. (Generally, thatâs a good thing, as you donât want a JavaScript error to interrupt the experience of viewing your web pages.)
So how do you figure out whatâs gone wrong? There are many ways to track errors in a JavaScript program. Youâll learn some advanced debugging techniques in Chapter 17, but the most basic method is to consult the web browser. Most web browsers keep track of JavaScript errors and record them in a separate window called an error console. When you load a web page that contains an error, you can then view the console to get helpful information about the error, like which line of the web page it occurred in and a description of the error.
Often, you can find the answer to the problem in the error console, fix the JavaScript, and then the page will work. The console helps you weed out the basic typos you make when you first start programming, like forgetting closing punctuation, or mistyping the name of a JavaScript command. You can use the error console in your favorite browser, but because scripts sometimes work in one browser and not another, this section shows you how to turn on the JavaScript console in all major browsers, so you can track down problems in each.
Googleâs Chrome browser is beloved by many a web developer. Its DevTools feature gives you many ways to troubleshoot HTML, CSS, and JavaScript problems. Also, its JavaScript console is a great place to begin tracking down errors in your code. It not only describes the errors it finds, it also identifies the line in your code where each error occurred.
To open the JavaScript console, click the Customize menu button (circled in Figure 1-5) and choose ToolsâJavaScript Console. Or use the keyboard shortcut Ctrl+Shift+J (Windows) or â-Option-J (Mac).
Figure 1-5. 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.
After you open the console, you can examine any errors that appear in the current page. For example, in Figure 1-6, the console identifies the error as an âUncaught SyntaxError: Unexpected token ILLEGAL.â OK, it may not be immediately obvious what that means, but as you encounter (and fix) more errors youâll get 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â part just means that the browser has encountered an illegal character, or (and hereâs the tricky part) that thereâs a missing character. In this case, looking closely at the code you can see thereâs an opening single quote mark before âslowâ but no final quote mark.
The console also identifies the name of the file the error is in (complete_slide.html, in this case) and the line number the error occurs (line 10). Click the filename, and Chrome opens the file above the console and briefly highlights the line (see Figure 1-5).
Tip
Because the error console displays the line number where the error occurred, you may want to use a text editor that can show line numbers. That way, you can easily jump from the error console to your text editor and identify the line of code you need to fix.
Figure 1-6. 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).
Unfortunately, thereâs a long list of things that can go wrong in a script, from simple typos to complex errors in logic. When youâre just starting out with JavaScript programming, many of your errors will be the simple typographic sort. For example, you might forget a semicolon, quote mark, or parenthesis, or misspell a JavaScript command. Youâre especially prone to typos when following examples from a book (like this one). Here are a few common mistakes you might make and the (not-so obvious) error messages you may encounter:
Missing punctuation. As mentioned earlier, JavaScript programming often involves lots of symbol pairs like opening and closing parentheses and brackets. For example, if you type
alert(âhellOâ;
âleaving off the closing parenthesisâyouâll probably get the: âUnexpected token;â message, meaning 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 by quote marks (youâll learn about these in greater detail on Types of Data). For example, âhelloâ is a string in the code
alert(âhellOâ);
. Itâs 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 single-quote with a double quote like this:alert(âhelloâ);
. In either case, youâll probably see an âUncaught SyntaxError: Unexpected token ILLEGALâ error.Misspelling commands. If you misspell a JavaScript commandâ
aler(âhellOâ);
âyouâll get an error saying that the misspelled command isnât defined: for example, âUncaught ReferenceError: aler is not defined,â if you misspell thealert
command. Youâll also encounter problems when you misspell jQuery functions (like the.hide()
and.slideDown()
functions in the previous tutorial). In this case, youâll get a different error. For example, if you 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 do and provides this generic error message. A syntax error represents some mistake in your code. It may not be a typo, but you 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 you made. Unfortunately, these types of errors often require experience with and understanding of the JavaScript language to fix.
As you can see from the preceding list, many errors youâll make simply involve forgetting to type one of a pair of punctuation marksâlike quote marks or parentheses. Fortunately, these are easy to fix, and as you get more experience programming, youâll eventually stop making them almost completely (no programmer is perfect).
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 bottom half of the browser window. Press the F12 key 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).
Note
If you first open a web page and then open the Internet Explorer console, you wonât see any errors (even if there are some). You need to reload the page to see any errors. Once the console is open, youâll see errors on the pages you visit as they load.
IEâs Console displays error messages similar to those described earlier for Chrome. However, sometimes theyâre very different. For example, IEâs âUnterminated string constantâ is an âUnexpected token ILLEGALâ error in Chrome. Like Chrome, Internet Explorer identifies the line of code in the HTML file where the error occurred, which you can click to see the actual code where the error occurs.
Mozillaâs Firefox browser also gives you a console to view JavaScript errors. To open the JavaScript console, on Windows click the Firefox tab in the top left of the browser window and choose Web DeveloperâWeb Console. On a Mac, select ToolsâWeb DeveloperâWeb Console. Or use the keyboard shortcuts Ctrl+Shift+I (Windows) or â-Option-K (Mac).
Once the console opens, youâll see any JavaScript errors on the page. Unfortunately, Firefoxâs Web Console is more like a fire hose of data than a simple JavaScript error reporter (Figure 1-8). Thatâs 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âs Error Console. In fact, it provided the model for the developer tools in Internet Explorer, Chrome, and Safari (discussed next).
Figure 1-8. 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 âin,â like the Net, JS (short for JavaScript), and Logging buttons here.
Safariâs error console is available from the Develop menu: DevelopâShow Error Console (or, if youâre on a Mac, use the Option-â-C keyboard shortcut). However, the Develop menu isnât normally turned on when Safari is installed, so there are a couple of steps to get to the JavaScript console.
To turn on the Develop menu, you need to first access the Preferences window. Choose SafariâPreferences. Once the Preferences window opens, click the Advanced button. Turn on the âShow Develop menu in menu barâ box and close the Preferences window.
When you restart Safari, the Develop menu will appear between the Bookmarks and Window menus in the menu bar at the top of the screen. Select DevelopâShow Error Console to open the console (see Figure 1-9).
Figure 1-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.
Get JavaScript & jQuery: The Missing Manual, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.