Download Full JavaScript jQuery The Missing Manual Second Edition David Sawyer Mcfarland PDF All Chapters
Download Full JavaScript jQuery The Missing Manual Second Edition David Sawyer Mcfarland PDF All Chapters
com
https://ebookfinal.com/download/javascript-jquery-the-
missing-manual-second-edition-david-sawyer-mcfarland/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookfinal.com/download/css-the-missing-manual-david-sawyer-
mcfarland/
ebookfinal.com
https://ebookfinal.com/download/dreamweaver-cs4-the-missing-
manual-1st-edition-david-sawyer-mcfarland/
ebookfinal.com
https://ebookfinal.com/download/dreamweaver-cc-the-missing-manual-2nd-
edition-covers-2014-release-david-sawyer-mcfarland/
ebookfinal.com
https://ebookfinal.com/download/html5-the-missing-manual-second-
edition-matthew-macdonald/
ebookfinal.com
iPhone The Missing Manual 3G 2nd Edition David Pogue
https://ebookfinal.com/download/iphone-the-missing-manual-3g-2nd-
edition-david-pogue/
ebookfinal.com
https://ebookfinal.com/download/php-mysql-the-missing-manual-second-
edition-brett-mclaughlin/
ebookfinal.com
https://ebookfinal.com/download/david-pogue-s-digital-photography-the-
missing-manual-1st-edition-david-pogue/
ebookfinal.com
https://ebookfinal.com/download/mac-os-x-the-missing-manual-panther-
edition-david-pogue/
ebookfinal.com
https://ebookfinal.com/download/drupal-6-javascript-and-jquery-1st-
edition-matt-butcher/
ebookfinal.com
JavaScript &
jQuery
The book that should have been in the box
®
JavaScript &
jQuery 2nd Edition
Nutshell Handbook, the Nutshell Handbook logo, the O’Reilly logo, and “The book that should
have been in the box” are registered trademarks of O’Reilly Media, Inc. JavaScript & jQuery:
The Missing Manual, The Missing Manual logo, Pogue Press, and the Pogue Press logo are
trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc.,
was aware of a trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and
authors assume no responsibility for errors or omissions, or for damages resulting from the use
of the information contained herein.
ISBN: 978-1-449-3-9902-3
[M]
Table of Contents
v
Combining Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Combining Numbers and Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Changing the Values in Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Tutorial: Using Variables to Create Messages. . . . . . . . . . . . . . . . . . . . . . . . . 55
Tutorial: Asking for Information. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Creating an Array.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Accessing Items in an Array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Adding Items to an Array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Deleting Items from an Array. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Tutorial: Writing to a Web Page Using Arrays. . . . . . . . . . . . . . . . . . . . . . . . . 66
A Quick Object Lesson. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
When to Use Comments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Comments in This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
vi table of contents
Selecting Page Elements: The jQuery Way. . . . . . . . . . . . . . . . . . . . . . . . . . 129
Basic Selectors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Advanced Selectors.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
jQuery Filters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Understanding jQuery Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Adding Content to a Page.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Replacing and Removing Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Setting and Reading Tag Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Reading and Changing CSS Properties. . . . . . . . . . . . . . . . . . . . . . . . . 143
Changing Multiple CSS Properties at Once. . . . . . . . . . . . . . . . . . . . . . . 144
Reading, Setting, and Removing HTML Attributes. . . . . . . . . . . . . . . . . . . . . . 146
Acting on Each Element in a Selection. . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Anonymous Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
this and $(this). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Automatic Pull Quotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Programming.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
table of contents ix
Part Four: Ajax: Communication with the Web Server
Chapter 11: Introducing Ajax. . . . . . . . . . . . . . . . . . . . . . 341
What Is Ajax?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Ajax: The Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Pieces of the Puzzle. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
Talking to the Web Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Ajax the jQuery Way. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Using the load() Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Tutorial: The load() Function.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
The get() and post() Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Formatting Data to Send to the Server. . . . . . . . . . . . . . . . . . . . . . . . . 357
Processing Data from the Server.. . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Handling Errors.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
Tutorial: Using the get() Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
JSON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Accessing JSON Data.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Complex JSON Objects.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
x table of contents
Chapter 14: Going Further with JavaScript. . . . . . . . . . . . . . 425
Working with Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Determining the Length of a String. . . . . . . . . . . . . . . . . . . . . . . . . . . 425
Changing the Case of a String. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Searching a String: indexOf() Technique. . . . . . . . . . . . . . . . . . . . . . . . 427
Extracting Part of a String with slice(). . . . . . . . . . . . . . . . . . . . . . . . . . 428
Finding Patterns in Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
Creating and Using a Basic Regular Expression. . . . . . . . . . . . . . . . . . . . . 431
Building a Regular Expression. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
Grouping Parts of a Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
Useful Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Matching a Pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
Replacing Text. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Trying Out Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
Working with Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
Changing a String to a Number. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
Testing for Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Rounding Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Formatting Currency Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
Creating a Random Number. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
Dates and Times. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
Getting the Month. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
Getting the Day of the Week. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
Getting the Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
Creating a Date Other Than Today.. . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Putting It All Together. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Using External JavaScript Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
Writing More Efficient JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Putting Preferences in Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Ternary Operator.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
The Switch Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
Creating Fast-Loading JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
table of contents xi
Using console.log() to Track Script Progress. . . . . . . . . . . . . . . . . . . . . . 479
Tutorial: Using the Firebug Console. . . . . . . . . . . . . . . . . . . . . . . . . . . 481
More Powerful Debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
Debugging Tutorial. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
xiii
Acknowledgements
Carla Spoon (proofreader) is a freelance writer and copy editor. An avid runner, she
works and feeds her tech gadget addiction from her home office in the shadow of
Mount Rainier. Email: carla_spoon@comcast.net.
Angela Howard (indexer) has been indexing for more than 10 years, mostly for
computer books, but occasionally for books on other topics, such as travel, alterna-
tive medicine, and leopard geckos. She lives in California with her husband, daugh-
ter, and two cats.
Acknowledgements
Many thanks to all those who helped with this book, including Shelley Powers and
Steve Suehring, whose watchful eyes saved me from potentially embarrassing mis-
takes. Thanks also to my many students at Portland State University who have sat
through my long JavaScript lectures and struggled through my programming as-
signments—especially the members of Team Futzbit (Combination Pizza Hut and
Taco Bell) for testing the tutorials: Julia Hall, Amber Brucker, Kevin Brown, Josh
Elliott, Tracy O’Connor, and Blake Womack. Also, we all owe a big debt of grati-
tude to John Resig and the jQuery team for creating the best tool yet for making
JavaScript fun.
Finally, thanks to David Pogue for getting me started; Nan Barber for making my
writing sharper and clearer; my wife, Scholle, for putting up with an author’s cranki-
ness; and thanks to my kids, Graham and Kate, because they’re just awesome.
T
he Web was a pretty boring place in its early days. Web pages were constructed
from plain old HTML, so they could display information, and that was about
all. Folks would click a link and then wait for a new web page to load. That
was about as interactive as it got.
These days, most websites are almost as responsive as the programs on a desktop
computer, reacting immediately to every mouse click. And it’s all thanks to the subjects
of this book—JavaScript and its sidekick, jQuery.
What Is JavaScript?
JavaScript is a programming language that lets you supercharge your HTML with
animation, interactivity, and dynamic visual effects.
JavaScript can make web pages more useful by supplying immediate feedback. For
example, a JavaScript-powered shopping cart page can instantly display a total cost,
with tax and shipping, the moment a visitor selects a product to buy. JavaScript can
produce an error message immediately after someone attempts to submit a web form
that’s missing necessary information.
JavaScript also lets you create fun, dynamic, and interactive interfaces. For example,
with JavaScript, you can transform a static page of thumbnail images into an animated
slideshow (as you’ll learn how to do on page 314). Or you can do something more
subtle like stuff more information on a page without making it seem crowded by
organizing content into bite-size panels that visitors can access with a simple click of
the mouse (page 301). Or add something useful and attractive, like pop-up tooltips
that provide supplemental information for items on your web page (page 326).
1
What Is JavaScript?
Another one of JavaScript’s main selling points is its immediacy. It lets web pages
respond instantly to actions like clicking a link, filling out a form, or merely moving
the mouse around the screen. JavaScript doesn’t suffer from the frustrating delay
associated with server-side programming languages like PHP, which rely on com-
munication between the web browser and the web server. Because it doesn’t rely on
constantly loading and reloading web pages, JavaScript lets you create web pages that
feel and act more like desktop programs than web pages.
If you’ve visited Google Maps (http://maps.google.com), you’ve seen JavaScript in ac-
tion. Google Maps lets you view a map of your town (or pretty much anywhere else for
that matter), zoom in to get a detailed view of streets and bus stops, or zoom out to get
a birds-eye view of how to get across town, the state, or the nation. While there were
plenty of map sites before Google, they always required reloading multiple web pages
(usually a slow process) to get to the information you wanted. Google Maps, on the
other hand, works without page refreshes—it responds immediately to your choices.
The programs you create with JavaScript can range from the really simple (like pop-
ping up a new browser window with a web page in it) to full-blown web applications
like Google Docs (http://docs.google.com), which let you create presentations, edit
documents, and create spreadsheets using your web browser with the feel of a pro-
gram running directly on your computer.
A Bit of History
Invented by Netscape back in 1995, JavaScript is nearly as old as the web itself. While
JavaScript is well respected today, it has a somewhat checkered past. It used to be
considered a hobbyist’s programming language, used for adding less-than-useful
effects such as messages that scroll across the bottom of a web browser’s status bar
like a stock-ticker, or animated butterflies following mouse movements around the
page. In the early days of JavaScript, it was easy to find thousands of free JavaScript
programs (also called scripts) online, but many of those scripts didn’t work in all web
browsers, and at times even crashed browsers.
Note: JavaScript has nothing to do with the Java programming language. JavaScript was originally
named LiveScript, but the marketing folks at Netscape decided they’d get more publicity if they tried to
associate the language with the then-hot Java. Don’t make the mistake of confusing the two…especially
at a job interview!
In the early days, JavaScript also suffered from incompatibilities between the two
prominent browsers, Netscape Navigator and Internet Explorer. Because Netscape
and Microsoft tried to outdo each other’s browsers by adding newer and (ostensibly)
better features, the two browsers often acted in very different ways, making it difficult
to create JavaScript programs that worked well in both.
Note: After Netscape introduced JavaScript, Microsoft introduced jScript, their own version of JavaScript
included with Internet Explorer.
Fortunately the worst of those days is nearly gone and contemporary browsers like
Firefox, Safari, Chrome, Opera, and Internet Explorer 9 have standardized much of
the way they handle JavaScript, making it easier to write JavaScript programs that
work for most everyone. (There are still a few incompatibilities among current web
browsers, so you’ll need to learn a few tricks for dealing with cross-browser problems.
You’ll learn how to overcome browser incompatibilities in this book.)
In the past several years, JavaScript has undergone a rebirth, fueled by high-profile
websites like Google, Yahoo, and Flickr, which use JavaScript extensively to create
interactive web applications. There’s never been a better time to learn JavaScript.
With the wealth of knowledge and the quality of scripts being written, you can add
sophisticated interaction to your website—even if you’re a beginner.
Note: JavaScript is also known by the name ECMAScript. ECMAScript is the “official” JavaScript specifica-
tion, which is developed and maintained by an international standards organization called Ecma Interna-
tional: http://www.ecmascript.org/
JavaScript Is Everywhere
JavaScript isn’t just for web pages, either. It’s proven to be such a useful programming
language that if you learn JavaScript you can create Yahoo Widgets and Apple’s
Dashboard Widgets, write programs for the iPhone, and tap into the scriptable fea-
tures of many Adobe programs like Acrobat, Photoshop, Illustrator, and Dream-
weaver. In fact, Dreamweaver has always offered clever JavaScript programmers a
way to add their own commands to the program.
In addition, the programming language for Flash—ActionScript—is based on Java
Script, so if you learn the basics of JavaScript, you’ll be well prepared to learn Flash
programming.
What Is jQuery?
JavaScript has one embarrassing little secret: writing it is hard. While it’s simpler
than many other programming languages, JavaScript is still a programming lan-
guage. And many people, including web designers, find programming difficult. To
complicate matters further, different web browsers understand JavaScript differ-
ently, so a program that works in, say, Chrome may be completely unresponsive in
Internet Explorer 9. This common situation can cost many hours of testing on dif-
ferent machines and different browsers to make sure a program works correctly for
your site’s entire audience.
introduction 3
HTML: The
Barebones Structure
That’s where jQuery comes in. jQuery is a JavaScript library intended to make
JavaScript programming easier and more fun. A JavaScript library is a complex
JavaScript program that both simplifies difficult tasks and solves cross-browser
problems. In other words, jQuery solves the two biggest headaches with JavaScript—
complexity and the finicky nature of different web browsers.
jQuery is a web designer’s secret weapon in the battle of JavaScript programming.
With jQuery, you can accomplish tasks in a single line of code that would other-
wise take hundreds of lines of programming and many hours of browser testing to
achieve with your own JavaScript code. In fact, an in-depth book solely about Java
Script would be at least twice as thick as the one you’re holding; and, when you were
done reading it (if you could manage to finish it), you wouldn’t be able to do half of
the things you can accomplish with just a little bit of jQuery knowledge.
That’s why most of this book is about jQuery. It lets you do so much, so easily. An-
other great thing about jQuery is that you can add advanced features to your website
with thousands of easy-to-use jQuery plug-ins. For example, the FancyBox plug-in
(which you’ll meet on page 222) lets you take a simple page of thumbnail graphics
and turn it into an interactive slideshow—all with a single line of programming!
Unsurprisingly, jQuery is used on millions of websites (http://trends.builtwith.com/
javascript/JQuery). It’s baked right into popular content management systems like
Drupal and WordPress. You can even find job listings for “jQuery Programmers”
with no mention of JavaScript. When you learn jQuery, you join a large community
of fellow web designers and programmers who use a simpler and more powerful
approach to creating interactive, powerful web pages.
Note: For a full-fledged introduction to HTML and CSS, check out Head First HTML with CSS and XHTML
by Elisabeth Freeman and Eric Freeman. For an in-depth presentation of the tricky subject of Cascading
Style Sheets, pick up a copy of CSS: The Missing Manual by David Sawyer McFarland (both O’Reilly).
HTML (Hypertext Markup Language) uses simple commands called tags to define the
various parts of a web page. For example, this HTML code creates a simple web page:
Note: XHTML was once heralded as the next big thing for web designers. Although you’ll still find people
who think you should only use XHTML, the winds of change have turned. The World Wide Web Consor-
tium (W3C) has stopped development of XHTML in favor of HTML5. You can learn more about HTML5 by
picking up a copy of HTML5: The Missing Manual by Matthew MacDonald or HTML5: Up and Running by
Mark Pilgrim (both from O'Reilly).
introduction 5
HTML: The
Barebones Structure
commands. Sandwiched between brackets, these tags are instructions that tell a web
browser how to display the web page. Tags are the “markup” part of the Hypertext
Markup Language.
The starting (opening) tag of each pair tells the browser where the instruction begins,
and the ending tag tells it where the instruction ends. Ending or closing tags always
include a forward slash (/) after the first bracket symbol (<). For example, the tag
<p> marks the start of a paragraph, while </p> marks its end.
For a web page to work correctly, you must include at least these three tags:
• The <html> tag appears once at the beginning of a web page (after the doctype)
and again (with an added slash) at the end. This tag tells a web browser that the
information contained in this document is written in HTML, as opposed to
some other language. All of the contents of a page, including other tags, appear
between the opening and closing <html> tags.
If you were to think of a web page as a tree, the <html> tag would be its trunk.
Springing from the trunk are two branches that represent the two main parts of
any web page—the head and the body.
• The head of a web page, surrounded by <head> tags, contains the title of the
page. It may also provide other, invisible information (such as search keywords)
that browsers and web search engines can exploit.
In addition, the head can contain information that’s used by the web browser for
displaying the web page and for adding interactivity. You put Cascading Style
Sheets, for example, in the head of the document. The head of the document is
also where you often include JavaScript programming and links to JavaScript files.
• The body of a web page, as set apart by its surrounding <body> tags, contains all
the information that appears inside a browser window: headlines, text, pictures,
and so on.
Within the <body> tag, you commonly find tags like the following:
• You tell a web browser where a paragraph of text begins with a <p> (opening
paragraph tag), and where it ends with a </p> (closing paragraph tag).
• The <strong> tag emphasizes text. If you surround some text with it and its part-
ner tag, </strong>, you get boldface type. The HTML snippet <strong>Warning!
</strong> tells a web browser to display the word “Warning!” in bold type.
• The <a> tag, or anchor tag, creates a hyperlink in a web page. When clicked, a
hyperlink—or link—can lead anywhere on the web. You tell the browser where
the link points by putting a web address inside the <a> tags. For instance, you
might type <a href=“http://www.missingmanuals.com”>Click here!</a>.
The browser knows that when your visitor clicks the words “Click here!” it
should go to the Missing Manual website. The href part of the tag is called an at-
tribute and the URL (the Uniform Resource Locator or web address) is the value.
In this example, http://www.missingmanuals.com is the value of the href attribute.
UP TO SPEED
introduction 7
CSS: Adding Style to
Web Pages
create a CSS rule to make all <h1> tags appear 36 pixels tall, in the Verdana font, and
in orange. CSS can do more powerful stuff, too, like add borders, change margins,
and even control the exact placement of a page element.
When it comes to JavaScript, some of the most valuable changes you make to a page
involve CSS. You can use JavaScript to add or remove a CSS style from an HTML
tag, or dynamically change CSS properties based on a visitor’s input or mouse clicks.
You can even animate from the properties of one style to the properties of another
(say, animating a background color changing from yellow to red). For example, you
can make a page element appear or disappear simply by changing the CSS display
property. To animate an item across the screen, you can change the CSS position
properties dynamically using JavaScript.
Anatomy of a Style
A single style that defines the look of one element is a pretty basic beast. It’s essentially
a rule that tells a web browser how to format something—turn a headline blue, draw
a red border around a photo, or create a 150-pixel-wide sidebar box to hold a list of
links. If a style could talk, it would say something like, “Hey, Browser, make this look
like that.” A style is, in fact, made up of two elements: the web page element that the
browser formats (the selector) and the actual formatting instructions (the declaration
block). For example, a selector can be a headline, a paragraph of text, a photo, and so
on. Declaration blocks can turn that text blue, add a red border around a paragraph,
position the photo in the center of the page—the possibilities are endless.
Note: Technical types often follow the lead of the W3C and call CSS styles rules. This book uses the terms
“style” and “rule” interchangeably.
Of course, CSS styles can’t communicate in nice, clear English. They have their own
language. For example, to set a standard font color and font size for all paragraphs
on a web page, you’d write the following:
p { color: red; font-size: 1.5em; }
This style simply says, “Make the text in all paragraphs—marked with <p> tags—red
and 1.5 ems tall.” (An em is a unit or measurement that’s based on a browser’s nor-
mal text size.) As Figure I-1 illustrates, even a simple style like this example contains
several elements:
• Selector. The selector tells a web browser which element or elements on a page
to style—like a headline, paragraph, image, or link. In Figure I-1, the selec-
tor (p) refers to the <p> tag, which makes web browsers format all <p> tags
using the formatting directions in this style. With the wide range of selectors
that CSS offers and a little creativity, you can gain fine control of your pages’
formatting. (Selectors are an important part of using jQuery, so you’ll find a
detailed discussion of them starting on page 129.)
Note: If you need to brush up on your CSS, grab a copy of CSS: The Missing Manual.
• Value. Finally, you get to express your creative genius by assigning a value to
a CSS property—by making a background blue, red, purple, or chartreuse, for
example. Different CSS properties require specific types of values—a color (like
red, or #FF0000), a length (like 18px, 2in, or 5em), a URL (like images/back-
ground.gif), or a specific keyword (like top, center, or bottom).
You don’t need to write a style on a single line as pictured in Figure I-1. Many styles
have multiple formatting properties, so you can make them easier to read by break-
ing them up into multiple lines. For example, you may want to put the selector and
opening brace on the first line, each declaration on its own line, and the closing
brace by itself on the last line, like so:
p {
color: red;
font-size: 1.5em;
}
It’s also helpful to indent properties, with either a tab or a couple of spaces, to visibly
separate the selector from the declarations, making it easy to tell which is which.
And finally, putting one space between the colon and the property value is optional,
but adds to the readability of the style. In fact, you can put as much white space be-
tween the two as you want. For example color:red, color: red, and color : red all work.
introduction 9
Software for
JavaScript
Programming
Software for JavaScript Programming
To create web pages made up of HTML, CSS, and JavaScript, you need nothing more
than a basic text editor like Notepad (Windows) or TextEdit (Mac). But after typing
a few hundred lines of JavaScript code, you may want to try a program better suited
to working with web pages. This section lists some common programs, some free
and some you can buy.
Note: There are literally hundreds of tools that can help you create web pages and write JavaScript
programs, so the following is by no means a complete list. Think of it as a greatest-hits tour of the most
popular programs that JavaScript fans are using today.
Free Programs
There are plenty of free programs out there for editing web pages and style sheets.
If you’re still using Notepad or TextEdit, give one of these a try. Here’s a short list to
get you started:
• Notepad++ (Windows, http://notepad-plus-plus.org) is a coder’s friend. It high-
lights the syntax of JavaScript and HTML code, and lets you save macros and
assign keyboard shortcuts to them so you can automate the process of inserting
the code snippets you use most.
• HTML-Kit (Windows, www.chami.com/html-kit) is a powerful HTML/XHTML
editor that includes lots of useful features, like the ability to preview a web page
directly in the program (so you don’t have to switch back and forth between
browser and editor), shortcuts for adding HTML tags, and a lot more.
• CoffeeCup Free HTML Editor (Windows, www.coffeecup.com/free-editor) is
the free version of the commercial ($49) CoffeeCup HTML editor.
• TextWrangler (Mac, www.barebones.com/products/textwrangler) is free software
that’s actually a pared-down version of BBEdit, the sophisticated, well-known
text editor for the Mac. TextWrangler doesn’t have all of BBEdit’s built-in HTML
tools, but it does include syntax-coloring (highlighting tags and properties in
different colors so it’s easy to scan a page and identify its parts), FTP support (so
you can upload files to a web server), and more.
• Eclipse (Windows, Linux, Mac; www.eclipse.org) is a free, popular choice
amongst Java Developers, but includes tools for working with HTML, CSS,
and JavaScript. A version specifically for JavaScript developers is also available
(www.eclipse.org/downloads/packages/eclipse-ide-javascript-web-developers/
indigor), as well as Eclipse plug-ins to add autocomplete for jQuery (http://
marketplace.eclipse.org/category/free-tagging/jquery).
• Aptana Studio (Windows, Linux, Mac; www.aptana.org) is a powerful, free
coding environment with tools for working with HTML, CSS, JavaScript, PHP,
and Ruby on Rails.
Commercial Software
Commercial website development programs range from inexpensive text editors to
complete website construction tools with all the bells and whistles:
• EditPlus (Windows, www.editplus.com) is an inexpensive ($35) text editor that
includes syntax-coloring, FTP, auto-completion, and other wrist-saving features.
• CoffeeCup (Windows, www.coffeecup.com) is a combination text and visual
editor ($49). You can either write straight HTML code or use a visual interface
to build your pages.
• textMate (Mac, http://macromates.com) is a darling of Mac programmers. This
text editor ($57) includes many timesaving features for JavaScript programmers,
like “auto-paired characters,” which automatically plops in the second character
of a pair of punctuation marks (for example, the program automatically inserts
a closing parenthesis after you type an opening parenthesis).
• BBEdit (Mac, www.barebones.com/products/bbedit). This much-loved Mac text
editor ($99.99) has plenty of tools for working with HTML, XHTML, CSS,
JavaScript, and more. It includes many useful web building tools and shortcuts.
• Dreamweaver (Mac and Windows, www.adobe.com/products/dreamweaver.html)
is a visual web page editor ($399.) It lets you see how your page looks in a web
browser. The program also includes a powerful text editor for writing JavaScript
programs and excellent CSS creation and management tools. Check out Dream-
weaver CS5.5: The Missing Manual for the full skinny on how to use this power-
ful program.
• Expression Web Designer (Windows, www.microsoft.com/expression/products/
StudioWebPro_Overview.aspx) is Microsoft’s entry in the web design field
($149). It includes many professional web design tools, including excellent
CSS features.
introduction 11
About This Book
Note: This book periodically recommends other books, covering topics that are too specialized or tan-
gential for a manual about using JavaScript. Sometimes the recommended titles are from Missing Manual
series publisher O’Reilly Media—but not always. If there’s a great book out there that’s not part of the
O’Reilly family, we’ll let you know about it.
way: You could build a house by cutting down and milling your own lumber, con-
structing your own windows, doors, and doorframes, manufacturing your own tile,
and so on. That “do it yourself ” approach is common to a lot of JavaScript books.
But who has that kind of time? This book’s approach is more like building a house by
taking advantage of already-built pieces and putting them together using basic skills.
The end result will be a beautiful and functional house built in a fraction of the time
it would take you to learn every step of the process.
Note: You’ll find step-by-step instructions for setting up a web server on your computer so you can take
advantage of the cool technology (discussed in Part 3) on this book’s companion web page. See “Living
Examples” on page 16 for details.
introduction 13
The Very Basics
• Part 5, Troubleshooting, Tips, and Tricks, takes you past the basics, covering
more complex concepts. You’ll learn more about how to use jQuery effectively,
as well as delve into advanced jQuery functions. This part of the book also helps
you when nothing seems to be working: when your perfectly crafted JavaScript
program just doesn’t seem to do what you want (or worse, it doesn’t work at
all!). You’ll learn the most common errors new programmers make as well as
techniques for discovering and fixing bugs in your programs.
At the end of the book, an appendix provides a detailed list of references to aid you
in your further exploration of the JavaScript programming language.
Tip: If you’re on a Mac and don’t have a right mouse button, you can accomplish the same thing by
pressing the Control key as you click with the one mouse button.
About→These→Arrows
Throughout this book, and throughout the Missing Manual series, you’ll find sen-
tences like this one: “Open the System→Library→Fonts folder.” That’s shorthand for
a much longer instruction that directs you to open three nested folders in sequence,
like this: “On your hard drive, you’ll find a folder called System. Open that. Inside
the System folder window is a folder called Library; double-click it to open it. In-
side that folder is yet another one called Fonts. Double-click to open it, too.”
Similarly, this kind of arrow shorthand helps to simplify the business of choosing
commands in menus, as shown in Figure I-2.
Figure I-2:
In this book, arrow notations help sim-
plify menu instructions. For example,
View→Text Size→Increase is a more
compact way of saying, “From the
View menu, choose Text Size; from the
submenu that then appears, choose
Increase.”
introduction 15
About the Online
Resources
Living Examples
As you read the book’s chapters, you’ll encounter a number of living examples—
step-by-step tutorials that you can build yourself, using raw materials (like graphics
and half-completed web pages) that you can download from either www.sawmac
.com/js2e or from this book’s Missing CD page at www.missingmanuals.com/cds. You
might not gain very much from simply reading these step-by-step lessons while re-
laxing in your porch hammock, but if you take the time to work through them at the
computer, you’ll discover that these tutorials give you unprecedented insight into the
way professional designers build web pages.
You’ll also find, in this book’s lessons, the URLs of the finished pages, so that you can
compare your work with the final result. In other words, you won’t just see pictures
of JavaScript code in the pages of the book; you’ll find the actual, working web pages
on the Internet.
Registration
If you register this book at oreilly.com, you’ll be eligible for special offers—like
discounts on future editions of JavaScript & jQuery: The Missing Manual. Register-
ing takes only a few clicks. To get started, type www.oreilly.com/register into your
browser to hop directly to the Registration page.
Feedback
Got questions? Need more information? Fancy yourself a book reviewer? On our
Feedback page, you can get expert answers to questions that come to you while read-
ing, share your thoughts on this Missing Manual, and find groups for folks who
share your interest in JavaScript and jQuery. To have your say, go to www.missing
manuals.com/feedback.
Errata
In an effort to keep this book as up to date and accurate as possible, each time we
print more copies, we’ll make any confirmed corrections you’ve suggested. We also
note such changes on the book’s website, so you can mark important corrections into
your own copy of the book, if you like. Go to http://tinyurl.com/jsjqtmm to report an
error and view existing corrections.
introduction 17
Part One: Getting Started
1
with JavaScript
Chapter 1: Writing Your First JavaScript Program
Chapter 2: The Grammar of JavaScript
Chapter 3: Adding Logic and Control to Your Programs
chapter
1
B
y 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, and click links to move to other web pages with more text and pictures.
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 and effective.
21
Introducing
Programming
Note: Actually, HTML5 does add some smarts to HTML—including basic form validation. But since 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 Mark Pilgrim’s HTML5: Up and Running (O’Reilly).
Introducing Programming
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 program-
ming concepts aren’t difficult to grasp, and as programming languages go, JavaScript
is relatively friendly to nonprogrammers.
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 ({ } [ ] ; , ()
UP TO SPEED
</script>
</head>
The <script> tag’s type attribute indicates the format and the type of script that fol-
lows. 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 page 7 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">
<head>
<title>My Web Page</title>
<script>
alert('hello world!');
</script>
</head>
You’ll find out what this JavaScript actually 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 HTML of the
page. 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. It’s even common to put <script> tags just below
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>
UP TO SPEED
URL Types
When attaching an external JavaScript file to a web page, the about folder, while the /scripts/site.js means go to the
you need to specify a URL for the src attribute of the scripts folder and get the file site.js.
<script> tag. A URL or Uniform Resource Locator is a
Here are some tips on which URL type to use:
path to a file located on the web. There are three types of
paths: absolute path, root-relative path, and document- • If you’re pointing to a file that’s not on the same serv-
relative path. All three indicate where a web browser can er as the web page, you must use an absolute path.
find a particular file (like another web page, a graphic, or It’s the only type that can point to another website.
a JavaScript file). • Root-relative paths are good for JavaScript files stored
on your own site. Since they always start at the root
An absolute path is like a postal address—it contains all the
folder, the URL for a JavaScript file will be the same
information needed for a web browser located anywhere
for every page on your website, even when web
in the world to find the file. An absolute path includes
pages are located in folders and subfolders on your
http://, the hostname, and the folder and name of the file.
site. However, root-relative paths don’t work unless
For example: http://www.cosmofarmer.com/scripts/site.js.
you’re viewing your web pages through a web server—
A root-relative path indicates where a file is located rela- either your web server out on the Internet, or a web
tive to a site’s top-level folder—the site’s root folder. A root- server you’ve set up on your own computer for test-
relative path doesn’t include http:// or the domain name. It ing purposes. In other words, if you’re just opening
begins with a / (slash) indicating the site’s root folder—the a web page off your computer using the browser’s
folder the home page is in. For example, /scripts/site.js File→Open command, the web browser won’t be
indicates that the file site.js is located inside a folder named able to locate, load, or run JavaScript files that are
scripts, which is itself located in the site’s top-level folder. attached using a root-relative path.
An easy way to create a root-relative path is to take an • Document-relative paths are the best when you’re
absolute path and strip off the http:// and the host name. designing on your own computer without the aid of a
For example, http://www.sawmac.com/index.html written web server. You can create an external JavaScript file,
as a root-relative URL is /index.html. attach it to a web page, and then check the JavaScript
A document-relative path specifies the path from the web in a web browser simply by opening the web page off
page to the JavaScript file. If you have multiple levels of your hard drive. Document-relative paths work fine
folders on your website, you’ll need to use different paths when moved to your actual, living, breathing website
to point to the same JavaScript file. For example, sup- on the Internet, but you’ll have to rewrite the URLs
pose you have a JavaScript file named site.js located in a to the JavaScript file if you move the web page to
folder named scripts in your website’s main directory. The another location on the server. In this book, we’ll be
document-relative path to that file will look one way for using document-relative paths, since they will let you
the home page—scripts/site.js—but for a page located in- follow along and test the tutorials on your own com-
side a folder named about, the path to the same file would puter without a web server.
be different; ../scripts/site.js—the ../ means climb up out of
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 bar, and another that lets you add a nifty slideshow to a
page of photos (you’ll learn how to do that on page 222). On your photo gallery page,
you’d want to have both JavaScript programs, so you’d attach both files.
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 page 33.
Note: The tutorials in this chapter require the example files from this book’s website, www.sawmac.com/
js2e/. Click the “Download tutorials” link to download them. (The tutorial files are stored as a single Zip file.)
Windows users should 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. Mac users, just double-click the file to decompress it. After you’ve downloaded and
decompressed the files, you should have a folder named MM_JAVASCRIPT2E on your computer, contain-
ing 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:
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 paren-
theses, and single-quote marks from your first script, for example). Make sure you include both opening
and closing punctuation marks when they’re required.
Although this first program isn’t earth-shatteringly complex (or even that in-
teresting), 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.
Note: Internet Explorer (IE) doesn’t like to run JavaScript programs contained in web pages that you open
directly off your hard drive, for fear that the JavaScript program might do something harmful. So when
you try to preview the tutorial files for this book in Internet Explorer, you’ll see a message saying that IE
has blocked the script. Click “Allow blocked content” to see the program run. This annoying behavior only
applies to web pages you preview from your computer, not from files you put up on a web server. When
following along with the tutorials in this book, it’s better to preview pages in a different web browser like
Firefox, Chrome, or Safari, so you can avoid having to hit the “Allow blocked content” button each time
you view your pages.
Figure 1-3:
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.
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. It’s important to start out with a full under-
standing of the basics. You’ll be doing some very useful and complicated things us-
ing 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.
This list, long as it is, is absolutely confined to the sources for the
story of the war, and that, too, of its main incidents. Were the
sources for the history of Greece before the opening of the fifth
century, for the non-Hellenic history, or even for minor incidents of
the war, to be taken into consideration, their discussion would extend
to many chapters.
The most remarkable general characteristic about this aspect of
his work is the composite, sometimes extremely composite, nature of
the sources employed in drawing up the account of any single one of
the main incidents. A second characteristic, hardly less remarkable,
is that those parts of his work whose truth is most conspicuously
demonstrable originate in the majority of cases in the historian’s
personal observation and personal inquiry.
Autopsy, and
The most noticeable examples of the accuracy of
the evidence his personal observation, and of the diligence and
of eye- care of his inquiries from persons who were present at
witnesses.
events, is afforded by the correctness with which he
describes the topography of Thermopylæ and Platæa, and the close
agreement of the incidents of those battles as recorded by him with
the nature and accidents of the ground at the present day. There is
no single statement of pure fact in his accounts of those battles upon
which suspicion is thrown by a minute examination of the areas
within which they were fought. The majority of them are positively
capable of proof by the results of such an examination. The manifest
errors in these two accounts do not lie in statement of fact, but in
statement of motive, and are fully explicable by the circumstances
under which the story was told. In neither case does he produce any
evidence that he was able to get information as to the motives which
influenced those in command. The story of the fighting in both cases
is a soldier’s story. The details of the first two days of the defence of
Thermopylæ were derived from some one who was present at, or a
spectator of, the fight, of which there were many survivors. Those of
the final scene are of the same character, though in that case it is
more difficult to conjecture who was the informant. From certain
indications in the story, it seems that parts of it
AUTOPSY AND
TOPOGRAPHY.
at any rate may have been derived from some
one who viewed it from the Persian side,
possibly some Malian who had been temporarily impressed as a
servant, and with whom Herodotus conversed when he visited the
spot in later years. Such are the details (vii. 208) with regard to some
of the Lacedæmonians being hidden from view of the Persian scout
by the interposition of the wall, and some of the information given
with reference to Epialtes (vii. 213). It is quite beyond question that
Herodotus had traversed the ground. His topographical information
can be followed in detail by any one who visits the region at the
present day.
The only uncertainty concerns the exact sites of one or two places
which he mentions outside the area of fighting, such as the
Amphiktyonic temple; but even these are identifiable with high
probability; and it is the use of the spade, not Herodotus’ information,
which is wanting.
The rest of his information with regard to Thermopylæ, with the
sole exception of the copies of the inscriptions on the monuments, is
232
traditional in origin, emanating from Sparta.
Artemisium he may have seen in the distance in the course of a
land journey from the north. The knowledge which he displays of
Halos, in his account of Xerxes’ visit to the place, renders it probable
that he had traversed the route which leads round the east end of
Othrys on to the Malian plain, and in going that way he would pass in
full view of Aphetæ and Artemisium. His topographical description of
these places is, in so far as it is called for, accurate enough. That is,
however, the only portion of the Artemisium story which can be set
down to aught of the nature of personal examination. Nor, indeed,
can any part of that story be safely attributed to the evidence of an
eye-witness of events. The list of the contingents of the Greek fleet
may be taken from official records of some sort; the rest of the story
seems to be drawn from tradition.
The tale of Salamis is, perhaps, the most extraordinary in the
whole of his history. There can be little doubt that when he wrote it
he had in his possession notes of information given him by some
one who was present at the battle. Probably he never compiled its
history of the battle until some years after he had taken the notes, at
a time when his informant was not within his reach, possibly dead
and gone. He must have known the topography of the strait; he
could hardly have lived in Athens without doing so.
How did he come to make the serious error which he undoubtedly
did make? There may be differences of opinion as to the nature of
the error, still more as to its cause; but as to the existence of it the
topographical evidence, as well as the contemporary account of the
eye-witness Æschylus, leave no reasonable doubt. The mistake
does not appear, in so far as can be judged, to have existed in his
original information. His account, despite the confusion inevitable to
the nature of his mistake, points to its being founded on evidence
which may have been in all essential particulars in accord with that
of Æschylus and Diodorus. The matter has already been discussed
at length in reference to the battle itself. Suffice it now to say that the
most probable explanation of it is that, using his notes of information
some time after they had been given him, he mistimed a movement
mentioned in them, and by so doing threw his narrative out of gear.
In the Salamis story, as elsewhere, the traditional element is
present in various forms. As in the case of Artemisium, the list of the
ships may be founded upon an official basis.
The story of Platæa is, perhaps, the most remarkable that he
wrote. How he ever arrived at the truth with regard to that scene of
confused fighting must excite the wonder of every student of history.
It is plain that he was peculiarly well satisfied
FACTS AND
JUDGMENTS.
with his evidence, for he was not in the habit of
treating at length incidents whose description
rested on testimony with which he was dissatisfied, however
important these incidents might be. His account of Marathon affords
proof of that; and there other ominous silences in his narrative which
can only have been due to lack of reliable information. His
topographical evidence on Platæa is undoubtedly due to autopsy.
Not merely are his direct statements on the subject marvellously
correct; but the whole of the topography implied in his account of the
many incidents of the battle is marvellously correct also. His
information was manifestly derived from one who had fought at
Platæa; and the character of the story is such as to render it possible
that he not merely visited the scene of it himself, but visited in
company with one who had fought there. His account exemplifies in
a peculiar way both his excellences and his limitations as a military
historian. His own diligent inquiry led him to make the best use
possible of the evidence at his command; but that evidence was not
obtained from one who was conversant with the plans of those who
directed the operations, nor had the historian himself such
knowledge and experience as would enable him to form sound
inductions as to the nature of those plans from information of the
kind which was at his disposal.
The traditional element in his account of Platæa is probably far
less in proportion than that in any one of the longer sections of his
history. Of official record only the list of the Greek contingents shows
probable traces.
Such are the major parts of his history in which the evidence of
autopsy on his part, or on the part of his sources of information, is
most strikingly displayed.
One minor passage, that relating to Xerxes’ visit to the vale of
Tempe, must be mentioned. The considerations on the physical
geography of Thessaly, which are put into the mouth of the Great
King, are almost certainly those of the historian himself, derived from
his personal knowledge of the region. This view is further supported
by the remark he makes on his own authority in reference to the
withdrawal of the Greek force from that region, that he believes it
was due to the discovery that Tempe was not the only pass into the
country from the north.
With regard to the other two great battle-grounds of this period,
the evidence of autopsy is doubtful Herodotus’ account of Marathon
makes it probable that he had not seen the ground. His account of
the battle, such as it is, is marked by certain mistaken deductions,
probably his own, resting on a basis of misinformation. The
remainder of it is obviously traditional in origin.
Whether Herodotus had ever seen the ground at Mykale is very
doubtful. He certainly had never examined it in detail. It is, however,
quite possible that some of his information with regard to it was
drawn from an eye-witness.
Oracles.
Mention has already been made of certain traces of
the use of official records of a secular origin. It now
remains to consider those oracular responses, whose actual wording
in their official written form came under his notice, whether at the
place at which they were delivered, or in the city to which they were
given. The great difficulty is to determine whether, in the individual
cases in which he quotes oracles, his quotation is drawn from an
official version, or from a version accepted by tradition. Positive
cases of the latter mode of quotation are more easy to recognize
than positive cases of the former; though in nearly all cases alike he
gives what purports to be, and may be, the actual wording of the
response. Nevertheless, the two kinds of quotation demand that the
material quoted, even if identical in form, should be regarded as
coming under two different classes of evidence. It must not be
necessarily assumed that an oracle copied from an official record at
Delphi is better historical evidence than one preserved in the
memory of those to whom it was delivered. It is too probable that the
opposite is the case. There are many strong reasons for the
suspicion that in certain instances the hand of the editor brought the
record up to date by alterations and additions made in the light of
after-events. The oracles relative to Salamis are a case in point.
Delphi did no doubt possess sources of
ORACLES.
information with regard to Greek politics
generally, which rendered it able to give very useful advice to those
who consulted it; but it is impossible to believe that either at Delphi,
or anywhere else, the course of the war could have been so far
calculated before the actual struggle began, as that the
circumstances which made it so imperative to fight at Salamis should
have been foreseen.
It is in the history of the period at which apparently this oracle was
delivered, when the Greek states to which the council of defence had
appealed for help were making up their minds what attitude to adopt
in the coming war, that Herodotus makes most use of the evidence
of oracles. There is no reason, save in the case of the Salamis
oracle above mentioned, to suspect that those which he quotes are
in aught but their original form. They show that Delphi had a definite
policy at the time, founded upon the conviction that Athens, and
Athens alone, was the goal of the Persian expedition; and even after
the war was over Delphi might have argued with some show of
reason, though not on the solid basis of fact, that, had its advice
been followed, its conviction would have turned out true.
One other very important oracle quoted by Herodotus with
reference to the history of the war, is that which was alleged to have
brought about the self-sacrifice of Leonidas. From the way in which
the historian mentions it, it is obvious that he did not draw it from any
source independent of the tradition of the battle, to which, indeed, it
supplied the main motive.
Traditions.
It is often very difficult to trace with anything
approaching certainty the exact source of the various
traditions which Herodotus followed in different minor sections of his
history. In some cases it is only possible to make a guess at their
origin; and a discussion of them, not in itself very profitable, is but
too apt to lead to even less profitable results. It is quite certain, as
has been already said, that in many parts of his narrative he
combined information of very diverse origin and of very various
value.
A statement in a sentence in the midst of a long passage
oftentimes shows that its origin differs from that of its context. It is
not proposed to deal with such variations of the general pattern, but
to seek rather to arrive at some definite conclusion as to the
“provenance” of the chief authorities lying behind the main sections
of the historian’s work.
The account of the Ionian revolt is, as it would appear, drawn
largely from traditional sources. It is, of course, probable that
Herodotus in his early years actually talked with men who had
played a part in it; but it is also probable, on the other hand, that he
had not at that period of his life any formed intention of writing his
history. The traditions which he followed were undoubtedly
unfavourable to the Ionians. They were also defective in information.
Their origin must certainly be attributed to the Asiatic coast of the
Ægean; and this fact, together with these two main characteristics
above mentioned, points to the Dorian Greeks of the cities of the
Carian coast, of which Halikarnassos, Herodotus’ birthplace, was
one, as having been mainly responsible for them.
The attitude of these Dorians at the time of the revolt would be
only too calculated to make them unfavourable to those who had
taken part in it. Such information as Herodotus could get from Ionian
sources would be coloured by mutual recriminations, and would not,
consequently, be calculated to disabuse his mind of its first
impression.
Some few examples of the use of official records and inscriptions
are apparent, but they are few and far between.
The Marathon story seems to be almost wholly traditional, derived
from two Athenian sources of opposite tendency,—the one
aristocratic, wherein the services of the Miltiades were brought into
prominence, the other democratic, wherein the medizing tendencies
of the Alkmæonidæ were, in so far as possible, disguised and
excused. These two versions, with additions of his own, Herodotus
has combined into his narrative; but there must have been a large
mass of matter in both traditions which he has rejected as unreliable,
probably owing to the absolute impossibility of reconciling the
statements in the one version with those in the other.
The confused history of the wars between
PARTIALITY OF
GREEK TRADITION.
Athens and Ægina, one of which falls within
the decade between 490 and 480, is related on
the basis of an Athenian version, which the historian himself has
probably edited in certain parts: but the whole tradition was so
confused that he has evidently been able to make comparatively little
out of it.
The sources for the period immediately preceding the war of 480
are, as might be expected in the history of a time at which many of
the less prominent of the Greek states appear on the stage, of a very
varied character. To the employment of the records at Delphi in this
part of the historian’s work reference has been already made; but, in
addition to these official records, he appears to have made use of
tradition surviving at Delphi itself, especially with reference to the
relations of the oracle with Athens at that particular time.
The main basis of his account of the negotiations with Gelo and of
the events in Sicily in the period immediately succeeding them is a
tradition which was current throughout European Greece, whose
manifest tendency was to exclude the Sicilian tyrant from all
participation, direct or indirect, in the struggle for Hellenic freedom.
He expressly mentions, indeed, that there was a Sicilian version
which differed from it in certain respects; but he evidently attached
but little importance to it. That he made a mistake in his choice of
authority there can be little doubt; but, apart from the natural
predisposition of one who knew the tale of tyranny on the Asiatic
coast, and had every reason to dislike it, the Greek version had
probably taken firm root by the time at which he collected his
materials. The Sicilian version, with its probable exaggerations, is
preserved in Diodorus.
In discussing the attitude of Argos at this time, he expressly
reproduces two traditions, giving his preference to that of local Argive
origin. The other was probably that which was carried current among
the Greeks who had been patriotic, though certain details in it
suggest that it was originally from an Athenian source; and part of it
originated more than thirty years after the war, at the time of the
233
negotiations which led to the mysterious Peace of Kallias.
The tale of the negotiations with Corcyra, as well as of Corcyra’s
attitude at the time of Salamis, rests on a tradition which was in all
probability current among all the patriot Greeks. Corcyra was never
popular. The social Greek hated its individualism as a state in the
Hellenic world.
The tradition which Herodotus reproduces relating to the motives
which prompted the advice given by Themistocles to the Athenians
regarding the mines at Laurion is all part of that Themistocles legend
which he has consistently followed. Its origin has been already
attributed to the aristocratic party in Athens.
The absence of any attempt to tone down the picture drawn of the
medism of the Northern states points to the fact that the materials for
it were furnished by tradition current among the patriot Greeks.
The tale of Thermopylæ is one of the few stories of greater length
in the history in which the traditional element is homogeneous
throughout. The actual facts of the fighting were probably obtained
from examination of the ground, combined with the evidence of eye-
witnesses. But the whole motive of the story—the causes, that is to
say, which produced these facts—was drawn from a tradition, one
and indivisible, and that tradition was of Lacedæmonian origin. It was
more than that; it was no popular tale, but an official version of
events. It became pan-Hellenic, for the very good reason that the
extraordinary circumstances of the battle did not render the
existence of any other version possible. It would be mere repetition
of a long argument to recapitulate the reasons for this view: they
have been already stated in dealing with the account of the battle
itself. The oracular element contained in it was quite sufficient to
prejudice Herodotus in its favour; but even he does not seem to have
been satisfied with the reasons put forward for leaving Leonidas to
his fate; and he was evidently in doubt as to the true facts of what
occurred on the last day of the defence of the pass.
The tale of Artemisium would appear to have been drawn from
two sources, both of them Athenian. The
PERSIAN SOURCES.
Themistocles legend of aristocratic origin is
interwoven with a pan-Athenian version, whose object was to
emphasize in every possible way the services of Athens to the
national cause at this period of the war, and the many difficulties she
encountered in combating the fatal policy of withdrawal to the
Isthmus.
The same pan-Athenian tradition, combined with the
Themistocles legend, shows itself in the account of the events
between Artemisium and the actual fighting at Salamis.
Alike in the accounts of Thermopylæ and Salamis, descriptions
are given of events which occurred on the Persian side; even
discussions which took place in the Persian Council of War are
reported in what profess to be the actual words used. The latter may
be dismissed with the remark that they are instances in which the
dramatic instinct got the better of the historical sense of the historian.
But it is impossible to say that the matter in the description and
discussions is wholly unhistorical. The prominence of Artemisia in
one of them suggests that it is founded on a Halikarnassian tradition
of his own day. The remainder may rest partly on traditions carried
back to Asia by Greeks who were with Xerxes’ army. Herodotus
himself, who had relations with Persians in high positions in later
times, may have derived incidental information from them. But these
Persian tales in his history of the war must be regarded as indicating
only the drift of the truth.
The tale of Salamis, in so far as it is not founded on notes from a
personal narrative, suggests an origin in pan-Hellenic tradition. The
credit given to the Æginetan on the one side, and to the Ionians on
the other, can only have been the outcome of general consent. No
doubt, the more or less personal details of the fighting are drawn
from a variety of sources, Ionian, Halikarnassian, Athenian, and what
not; and the tale of the would-be Corinthian cowardice shows
unmistakably the traces of the cloven foot of later Athenian enmity.
The comparative briefness of the tale of Mykale suggests that
Herodotus had not the opportunity of getting much information with
regard to that important battle. As it stands, it presents no certain
trace of origin, but is probably the version of the story which was
generally current in Greece. Despite its brevity, it is, in contrast with
the story of Marathon, one which raises no difficulties. The evidence
was not evidently large in quantity; but, such as it is, it has all the
appearance of having been sound. It affords, moreover, another
example of that fact, to which reference has been already made on
several occasions, that Herodotus did not write history on the basis
of testimony with which he was not satisfied.
The view adopted in this volume on the right use of Herodotus’
work as a basis for history is not likely to commend itself to
extremists. It is perhaps due to the strong personality of the old
historian that his critics have at all times shown a tendency to divide
themselves into two camps, one of which champions not merely his
honesty, but his absolute accuracy, while the other bitterly assails
both. In a work so great and so extensive as his, it is almost
inevitable that the amount of accuracy obtained in various parts of it
should vary very greatly. The multiplicity, too, of his sources of
information would necessarily promote the same tendency.
As an historian he has suffered alike from his admirers and
detractors. He has been credited with a kind of inspiration. He has
been decried as a forger of history. It would be waste of time to
discuss views so extreme. Any one acquainted with the conditions
under which his history must have been composed will understand
the impossibility of attaining complete accuracy under such
circumstances. Any one who takes the trouble to examine the proofs
of the charges of forgery brought against him will know that they
have often been founded on mistaken premisses, and are in no
single instance convincing.
But there is an intermediate attitude taken towards his work by a
certain section of the learned world, about which a few words must
be said. There is a widespread tendency to
MODERN
CRITICISM.
adopt the view that, whatever the inaccuracies
contained in his writings, they represent the
high-watermark of knowledge attainable at the present day
concerning the period of Greek history of which he wrote; and that,
therefore, fertile criticism of his work aiming at any reconstruction of
the story is impossible. Such reconstructions are, moreover,
frequently stigmatized as attempts to read the ideas of the
nineteenth century after Christ into the history of the fifth century
before Christ. A charge, of the kind can only be founded on the
assumption that Herodotus was qualified not merely to record the
acts of the men of the period of which he wrote, but to appreciate to
the full the ideas and motives which produced the acts of those who
were presumably the most skilled men of their day in special
departments of life.
The evidence which is given in this volume, with respect at least
to the military history of this period, does not support such an
assumption. Putting aside detail, the general conclusions to which it
points are three in number:—
1. The extraordinary accuracy of statements of fact in Herodotus;
2. His lack of information as to the motives of those in command;
3. His lack of experience such as might have enabled him to form
deductions as to those motives.
If the evidence on which the first of these conclusions is founded
be held to justify it, it is not too much to assert that the modern world
is provided with the means of forming a sound judgment as to the
causes underlying the history of the most critical years of the fifth
century.
The debt of civilization to Herodotus does not require
exaggeration.
INDEX.
A
Bactrians, 418
Bakchylides, 28
Bithynia, 18, 60
Bœotia, Bœotians, 77, 228, 229 and n., 231, 252, 257, 262 n.,
275, 346 f.; routes, 346, 347, 350, 374, 407, 410, 439, 440,
445, and chap. xi. passim (especially 452, 455, 471, 477, 498,
505, 507, 512, 513, 519 ff.), 527, 544, 547, 549
Bosphorus, 50, 115
Boudenitza 265, 276, 346
Branchidæ [Temple of the], 22, 89
Brennus, 262 n., 265, 268 n., 281
Brygi, 150 f.
Bury, Prof., 357 n., 389, 390 n.
Busolt, 155 n.
Byzantion, 49, 50 n., 51 n., 56, 69, 99, 120 f., 135, 145, 518
Cadmus, 254 n.
Cambunian Mts., 231, 257
Cambyses, 36 f., 55, 255, 538
Cappadocia, 213
Caria, 18, 29, 31, 91, 99 ff., chap. iii. passim, 219, 338
Carrhæ, 426
Carthage, Carthaginians, 131, 245 ff., 254 ff. n., 355, 421–428,
523, 540
Cenchrea, 379
Chabrias, 456 n.
Chæronea, 347, 544
Chalkidike, 151, 429
Chalkis, 77, 134, 162, 265, 277, 320, 323 ff., 331, 332 and n., 342
f.; route, 347, 354 n., 469 n.
Charadra, 163 f. and chap. iv. passim
Charopinos, 94
Chileos, 442
Chilon, 344
Chios, 30, 83, 118, 120, 125, 129, 136 ff., 433, 530
Chronology, 107 f., 111, 114; revolt, chap. iii. passim, and 142–
144, 151, 172 f., 197 n., 198, 203 n., 229, 235, 237, 239, 240,
250, 251, 253 n., 271 f., 272 n., 319 f., 320 n., 330 f., 332 and
n., 342, 343, 377, 388, 390 n., 417, 427, 448
Cilicia, Cilicians, 106, 123, 148, 160, 219, 336 n., 343, 393, 402
Cimmerians, 10, 12
Clinton (Fasti), 203 n.
Constantine, 515
Constantinople, 515
Corcyra, 240 ff., 355 and n., 369 n., 576
Corinth, 21, 37, 77, 78, 205, 241, 270, 273, 306, 320, 328, 329,
339, 354 n., 355, 364 f., 367 f., 389 f., 398 n., 405, 469 n.; at
Platæa, 506, 517, 528, 535, 543, 563 f.
Cornelius Nepos, 184 n.
Corsica, 131
Creasy, Sir Edward, 407
Crete, Cretans, 235, 237, 240, 242
Crœsus, 18–28, 55, 97, 214, 349
Croiset, 362
Cyaxares, 15
Cyclades, 82