SlideShare a Scribd company logo
Visit https://ebookultra.com to download the full version and
explore more ebooks
Beginning JavaScript und CSS development with
jQuery 1. ed Edition Richard York
_____ Click the link below to download _____
https://ebookultra.com/download/beginning-javascript-
und-css-development-with-jquery-1-ed-edition-richard-
york/
Explore and download more ebooks at ebookultra.com
Here are some suggested products you might be interested in.
Click the link to download
Beginning CSS Cascading Style Sheets for Web Design Wrox
Beginning Guides 2nd Edition Richard York
https://ebookultra.com/download/beginning-css-cascading-style-sheets-
for-web-design-wrox-beginning-guides-2nd-edition-richard-york/
Joomla 1 5 JavaScript jQuery 1st Edition Jose Argudo
Blanco
https://ebookultra.com/download/joomla-1-5-javascript-jquery-1st-
edition-jose-argudo-blanco/
Beginning JavaScript 3rd ed Edition Paul Wilton
https://ebookultra.com/download/beginning-javascript-3rd-ed-edition-
paul-wilton/
Professional XMPP Programming with JavaScript and jQuery
1st Edition Jack Moffitt
https://ebookultra.com/download/professional-xmpp-programming-with-
javascript-and-jquery-1st-edition-jack-moffitt/
Beginning Windows Store Application Development HTML and
JavaScript Edition Scott Isaacs
https://ebookultra.com/download/beginning-windows-store-application-
development-html-and-javascript-edition-scott-isaacs/
Html 5 Black Book Covers Css 3 Javascript Xml Xhtml Ajax
Php And Jquery 2Ed 2nd Edition Dt Editorial Services
https://ebookultra.com/download/html-5-black-book-covers-
css-3-javascript-xml-xhtml-ajax-php-and-jquery-2ed-2nd-edition-dt-
editorial-services/
jQuery and JavaScript Phrasebook 1st Edition Brad Dayley
https://ebookultra.com/download/jquery-and-javascript-phrasebook-1st-
edition-brad-dayley/
Drupal 6 JavaScript and jQuery 1st Edition Matt Butcher
https://ebookultra.com/download/drupal-6-javascript-and-jquery-1st-
edition-matt-butcher/
Beginning JavaScript 5th Edition Jeremy Mcpeak
https://ebookultra.com/download/beginning-javascript-5th-edition-
jeremy-mcpeak/
Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York
Beginning JavaScript und CSS development with jQuery
1. ed Edition Richard York Digital Instant Download
Author(s): Richard York
ISBN(s): 9780470227794, 0470227796
Edition: 1. ed
File Details: PDF, 7.18 MB
Year: 2009
Language: english
Beginning
JavaScript®and CSS Development with jQuery
Richard York
27794ffirs.indd 5 3/16/09 3:14:20 PM
Beginning JavaScript® and CSS Development with jQuery
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-22779-4
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data
York, Richard.
Beginning JavaScript and CSS development with jQuery / Richard York.
p. cm.
Includes index.
ISBN 978-0-470-22779-4 (paper/website)
1. JavaScript (Computer program language) 2. Web sites--Design. 3. Cascading style sheets. I. Title.
QA76.73.J38Y67 2009
006.7’6--dc22
2009005636
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,
electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108
of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization
through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA
01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with
respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including
without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro-
motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold
with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If
professional assistance is required, the services of a competent professional person should be sought. Neither the publisher
nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this
work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses
the information the organization or Web site may provide or recommendations it may make. Further, readers should be
aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written
and when it is read.
For general information on our other products and services please contact our Customer Care Department within the
United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-
marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries,
and may not be used without written permission. JavaScript is a registered trademark of Sun Microsystems, Inc. All other
trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor
mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in
electronic books.
27794ffirs.indd 6 3/16/09 3:14:20 PM
Contents
Introduction xix
Part I: jQuery API 1
Chapter 1: Introduction to jQuery 3
What Does jQuery Do for Me? 4
Who Develops jQuery? 5
Obtaining jQuery 5
Installing jQuery 5
Programming Conventions 8
XHTML and CSS Conventions 9
JavaScript Conventions 16
Summary 25
Chapter 2: Selecting and Filtering 27
The Origin of the Selectors API 28
Using the Selectors API 29
Filtering a Selection 37
Searching within a Selection with find() 38
Finding an Element’s Siblings with siblings() 39
Selecting Specific Siblings 42
Searching Ancestors Using the parents() and parent() Methods 46
Selecting Children Elements 48
Selecting Elements via What You Don’t Want 50
Selecting a Snippet of the Results 51
Adding More Elements to a Selection 53
Selecting One Specific Element from a Result Set 55
Summary 66
Exercises 66
Chapter 3: Events 69
Assigning an Event with the Traditional Event Model 69
Assigning Events with the W3C Event Model 72
The this Object 73
The event Object 75
xii
Contents
The Microsoft JScript Event Model 77
Creating a Universal Event API 78
Binding Events with jQuery’s bind() Method 80
Binding Events with jQuery’s Event Methods 82
Triggering Events 83
Summary 93
Exercises 93
Chapter 4: Manipulating Content and Attributes 95
Setting and Accessing Attributes 95
Manipulating Class Names 105
Manipulating HTML and Text Content 109
Getting, Setting, and Removing Content 110
Appending and Prepending Content 115
Inserting Beside Content 123
Inserting Beside Content via a Selection 125
Wrapping Content 129
Replacing Elements 146
Removing Content 150
Cloning Content 154
Summary 162
Exercises 163
Chapter 5: Arrays and Iteration 165
Basic Iteration 165
Calling each() Directly 167
Variable Scope 168
Emulating break and continue 170
Iterating a Selection 172
Filtering Selections and Arrays 173
Filtering a Selection 174
Filtering a Selection with a Callback Function 175
Filtering an Array 177
Mapping a Selection or an Array 180
Mapping a Selection 180
Mapping an Array 183
Array Utility Methods 196
Making an Array 197
Finding a Value within an Array 197
xiii
Contents
Merging Two Arrays 198
Removing Duplicate Items 199
Summary 204
Exercises 205
Chapter 6: CSS 207
The css() Method 207
The outerWidth() and outerHeight() Methods 208
Summary 217
Exercises 217
Chapter 7: AJAX 219
Making a Server Request 220
What’s the Difference between GET and POST? 220
Formats Used to Transport Data with an AJAX Request 221
Making a GET Request with jQuery 222
Loading HTML Snippets from the Server 240
Dynamically Loading JavaScript 265
AJAX Events 267
Making an AJAX-Style File Upload 272
Summary 275
Exercises 276
Chapter 8: Effects 277
Showing and Hiding Elements 277
Sliding Elements 279
Fading Elements 280
Custom Animation 281
Summary 283
Exercises 284
Chapter 9: Plugins 285
Writing a Plugin 285
Good Practice for jQuery Plugin Development 295
Summary 296
Exercises 296
xiv
Contents
Part II: jQuery UI 297
Chapter 10: Implementing Drag-and-Drop 299
Making Elements Draggable 300
Making Elements Draggable with Ghosting 308
Dragging between Windows in Safari 311
Delegating Drop Zones for Dragged Elements 314
Summary 326
Exercises 326
Chapter 11: Drag-and-Drop Sorting 327
Making a List Sortable 327
Customizing Sortables 338
Saving the State of Sorted Lists 347
Summary 353
Exercises 354
Chapter 12: Selection by Drawing a Box 355
Introducing the Selectables Plugin 355
Summary 372
Exercises 372
Chapter 13: Accordion UI 373
Building an Accordion UI 373
Setting Auto-Height 376
Changing the Default Pane 377
Toggling the alwaysOpen Option 380
Changing the Accordion Event 380
Filling the Height of the Parent Element 381
Setting the Header Elements 381
Styling Selected Panes 384
Selecting a Content Pane by Location 387
Summary 390
Exercises 391
xv
Contents
Chapter 14: Datepicker 393
Implementing a Datepicker 393
Styling the Datepicker 395
Setting the Range of Allowed Dates 403
Allowing a Date Range to Be Selected 404
Localizing the Datepicker 405
Setting the Date Format 405
Localizing Datepicker Text 406
Changing the Starting Weekday 407
Summary 408
Exercises 408
Chapter 15: Dialogs 409
Implementing a Dialog 409
Examining a Dialog’s Markup 411
Making a Modal Dialog 417
Auto-Opening the Dialog 419
Controlling Dynamic Interaction 420
Animating the Dialog 421
Working with Dialog Events 422
Summary 423
Exercises 424
Chapter 16: Tabs 425
Implementing Tabs 425
Loading Remote Content via AJAX 432
Animating Tab Transitions 436
Summary 437
What Next? 437
Exercises 438
Appendix A: Answers to Exercises 439
Chapter 2 439
Chapter 3 439
Chapter 4 440
Chapter 5 441
xvi
Contents
Chapter 6 441
Chapter 7 442
Chapter 8 442
Chapter 9 443
Chapter 10 443
Chapter 11 444
Chapter 12 444
Chapter 13 444
Chapter 14 445
Chapter 15 445
Chapter 16 445
Appendix B: Selectors Supported by jQuery 447
Appendix C: Selecting and Filtering 451
Appendix D: Events 453
Event Object Normalization 455
Appendix E: Manipulating Attributes and Data Caching 457
Appendix F: Manipulating Content 459
Appendix G: AJAX Methods 461
Appendix H: CSS 465
Appendix I: Utilities 467
Appendix J: Draggables and Droppables 469
Appendix K: Sortables 475
Appendix L: Selectables 479
Notes 480
Appendix M: Effects 481
Speed 481
Callback Function 481
xvii
Contents
Appendix N: Accordion 485
Appendix O: Datepicker 487
Appendix P: Dialog 497
Appendix Q: Tabs 501
Appendix R: Re-Sizables 505
Appendix S: Sliders 509
Index 511
Introduction
The jQuery JavaScript framework is a rising star in the world of web development. JavaScript frame-
works in general have grown to become immensely popular in the past few years in parallel with the
ever-increasing presence of JavaScript-driven, so-called Web 2.0 websites that make heavy use of tech-
nologies like AJAX and JavaScript in general for slick graphical enhancements that would be impossible
or much more cumbersome to incorporate without JavaScript.
jQuery’s mission as a JavaScript library is simple — it strives to make the lives of web developers eas-
ier by patching over certain portions of cross-browser development and by making other tasks com-
monly needed by developers much easier. jQuery has the real, proven ability to reduce many lines of
plain-vanilla JavaScript to just a few lines, and, in many cases, just a single line. jQuery strives to
remove barriers to JavaScript development by removing redundancy wherever possible and normal-
izing cross-browser JavaScript development in key areas where browsers would otherwise differ,
such as Microsoft’s Event API and the W3C Event API, and other, more remedial tasks like getting the
mouse cursor’s position when an event has taken place.
jQuery is a compact, lightweight library that currently works in Microsoft’s Internet Explorer browser
from version 6 on, Firefox from version 1.5 on, Safari from version 2.0.2 on, Opera from version 9 on,
and Google’s new Chrome browser from version 0.2 on. Getting started with jQuery is very easy — all
you have to do is include a single link of markup in your HTML or XHTML documents that includes
the library. Throughout this book, I demonstrate jQuery’s API (Application Programming Interface)
components in detail and show you how all the nuts and bolts of this framework come together to
enable you to rapidly develop client-side applications.
I also cover the jQuery UI library, which makes redundant user-interface (UI) tasks on the client side
ridiculously easy and accessible to everyday web developers who might not have much JavaScript pro-
gramming expertise. Have you ever wanted to create an animated accordion effect like the one found
on Apple’s Mac home page at www.apple.com/mac? With jQuery, not only can you create this effect with
your own look and feel, but also it’s dead simple to boot.
Have you ever wondered how websites make virtual pop-up windows using JavaScript, HTML, and CSS?
The jQuery UI library provides the ability to create these pop-up windows and includes the ability to
animate transitions like fading the window on and off, or having it re-size from very small to full sized.
The jQuery UI library gives you the ability to use animations and transitions using JavaScript, markup,
and CSS that you may have thought previously could only have been done with Adobe’s Flash player.
The jQuery framework itself has enjoyed a great deal of mainstream exposure. It has been used by
Google, Dell, Digg, NBC, CBS, Netflix, The Mozilla Foundation, and the popular WordPress and Drupal
PHP frameworks.
jQuery is fast — superfast — and it has a small footprint. It’s only 15 KB, using the compressed and
gzipped version.
27794flast.indd 19 3/16/09 11:33:36 AM
Introduction
xx
jQuery gives you the ability to provide complex, professional, visually driven user interfaces and effects
with very few lines of code. What may have taken other developers days or even weeks to accomplish
can be done with jQuery in just a few hours.
Who This Book Is For
This book is for anyone interested in doing more with less code! You should have a basic understanding
of JavaScript. I review some basic JavaScript programming concepts, such as the Event API, but I do not
go into great detail about the JavaScript language itself. You’ll want to have at least a basic grasp of the
Document Object Model, or DOM, and basic JavaScript programming syntax. Additionally, you’ll need
to know your way around CSS and HTML, since knowledge of those technologies is also assumed. A
complete beginner might be able to grasp what is taking place in the examples in this book but might
not understand certain terminology and programming concepts that would be presented in a beginner’s
JavaScript guide, so if you are a beginner and insist with pressing forward, I recommend doing so with a
beginning JavaScript book on hand as well. Specifically, I recommend the following Wrox books for
more help with the basics:
Beginning Web Programming with HTML, XHTML, and CSS
❑
❑ , 2nd ed. (2008), by Jon Duckett
Beginning CSS: Cascading Style Sheets for Web Design
❑
❑ , 2nd ed. (2007), also written by yours truly.
Beginning JavaScript
❑
❑ , 3rd ed. (2007), by Paul Wilton and Jeremy McPeak
For further knowledge of JavaScript above and beyond what is covered in this book, I recommend
Professional JavaScript for Web Developers, 2nd ed. (2009), by Nicholas C. Zakas.
What This Book Covers
This book covers the jQuery JavaScript framework and the jQuery UI JavaScript framework and demon-
strates in great detail how to use the jQuery framework to get more results more quickly out of JavaScript
programming. I cover each method exposed by jQuery’s API, which contains methods to make common,
redundant tasks go much more quickly in less code. Some examples are methods that help you to select
elements from a markup document through the DOM and methods that help you to traverse through
those selections and filter them using jQuery’s fine-grained controls. This makes working with the DOM
easier and more effortless. I also cover how jQuery eliminates certain cross-browser, cross-platform devel-
opment headaches like the event model; not only does it eliminate these headaches, but it also makes it
easier to work with events by reducing the amount of code that you need to write to attach events. It even
gives you the ability to simulate events.
Later in the book, I cover how you can leverage the jQuery UI library to make graphically driven UI
widgets. jQuery gives you the ability to break content up among multiple tabs in the same page. You
have the ability to customize the look and feel of the tabs, and even to create a polished look and feel by
providing different effects that come in when you mouse over tabs and click on them. The jQuery UI
library also makes it easy to create accordion sidebars, like the one on Apple’s Mac website. These side-
bars have two or more panels, and when you mouse over an item, one pane transitions to another via a
smooth, seamless animation wherein the preceding pane collapses and the proceeding pane expands.
27794flast.indd 20 3/16/09 11:33:36 AM
Introduction
xxi
The jQuery UI library also gives you the ability to make any element draggable with the mouse; by click-
ing and holding and moving the mouse, you can move elements around on a page. It also makes it really
easy to create drag-and-drop user interfaces. This can be used to make a dropping zone where you take
elements from other parts of the page and drop them in another, as you would in your operating sys-
tem’s file manager when you want to move a folder from one place to another. You can also make lists
that are sortable via drag-and-drop, rearranging elements based on where you drop them. You can also
have a user interface where you drag the mouse cursor to make a selection, as you would in your oper-
ating system’s file manager when you want to select more than one file. Then jQuery UI also exposes the
ability to re-size elements on a page using the mouse. All of those neat things that you can do on your
computer’s desktop, you can also do in a web browser with jQuery UI.
jQuery UI also provides a widget for entering a date into a field using a nice, accessible JavaScript-
driven calendar that pops up when you click on an input field.
You can also make custom pop-up dialogues that are like virtual pop-up windows, except they don’t
open a separate browser window — they come up using markup, CSS, and JavaScript.
Another widget that jQuery UI provides is a graphical slider bar, similar to your media player’s volume
control.
As jQuery has done for JavaScript programming in general, jQuery UI strives to do for redundant
graphical user interface (GUI) tasks. jQuery UI gives you the ability to make professional user-interface
widgets with much less development effort.
If you’re interested in reading news about jQuery, how it’s evolving, and topics related to web develop-
ment, you may be interested in reading the official jQuery blog at blog.jquery.com, or jQuery’s creator,
John Resig’s blog, at www.ejohn.org.
If you are in need of help, you can participate in programming discussion at p2p.wrox.com, which
you can join for free to ask programming questions in moderated forums. There are also program-
ming forums provided by the jQuery community, which you can learn more about at
http://docs.jquery.com/Discussion.
Finally, I maintain a blog and website at www.deadmarshes.com, where you can contact me directly with
your thoughts about the book or read about the web development projects I’m working on.
How This Book Is Structured
This book is divided into two parts: The first half of the book covers the basic API exposed by the jQuery
library, and the second half covers the jQuery UI library.
Part 1: jQuery API
Chapter 1: Introduction to jQuery
❑
❑ — In this first chapter, I discuss a little of where jQuery came
from and why it was needed. Then I walk you through downloading and creating your first
jQuery-enabled JavaScript.
27794flast.indd 21 3/16/09 11:33:36 AM
Introduction
xxii
Chapter 2: Selecting and Filtering
❑
❑ — This chapter introduces jQuery’s selector engine, which
uses selectors like you will have used with CSS to make selections from the DOM. Then I talk
about the various methods that jQuery exposes for working with a selection, to give you fine-
grained control over what elements you’re working with from the DOM. I talk about methods
that let you select, ancestor elements, parent elements, sibling elements, descendent elements,
how to remove elements from a selection, how to add elements to a selection, and how to
reduce a selection to a specific subset of elements.
Chapter 3: Events
❑
❑ — In this chapter, I begin by reviewing the event model as you find it in plain-
vanilla JavaScript. You have the traditional event model, the W3C’s event model, and Microsoft’s
event model. I discuss the differences between these and why jQuery needed an entirely new
Event API to make the situation easier for web developers. Then I present jQuery’s Event API
and how you use it.
Chapter 4: Manipulating Content and Attributes
❑
❑ — In Chapter 4, you learn how to use the
methods that jQuery exposes for working with content, text and HTML, and element attributes.
jQuery provides methods for doing just about everything you’d want to do to an element.
Chapter 5: Arrays and Iteration
❑
❑ — In Chapter 5, I talk about how you can enumerate over a
selection of elements or an array using jQuery. As with everything else, jQuery provides an eas-
ier way that requires fewer lines of code to loop over the contents of an array or a selection of
elements from the DOM.
Chapter 6: CSS
❑
❑ — In this chapter, you learn about the methods that jQuery exposes for working
with CSS properties and declarations. jQuery provides intuitive and versatile methods that let
you manipulate CSS in a variety of ways.
Chapter 7: AJAX
❑
❑ — Chapter 7 elaborates on the methods that jQuery exposes for making AJAX
requests from a server, which allows you to request server content without working directly
with the XMLHttpRequest object and supports handling server responses in a variety of formats.
Chapter 8: Effects
❑
❑ — In Chapter 8, I discuss some helper methods that jQuery exposes for dis-
covering what browser and browser version you’re working with, whether you’re working with
a browser that supports the standard W3C box model for CSS, and a variety of odds and ends
methods for working with objects, arrays, functions, and strings.
Chapter 9: Plugins
❑
❑ — In this chapter, I describe how you can make your own plugins for jQuery.
Part II: jQuery UI
Chapter 10: Implementing Drag-and-Drop
❑
❑ — In Chapter 10, I begin my coverage of the jQuery
UI library by discussing how you make individual elements draggable and how you make a
drag-and-drop interface where you take one element and place it on top of another to create a
complete drag-and-drop sequence.
Chapter 11: Drag-and-Drop Sorting
❑
❑ — In Chapter 11, I discuss how you make lists sortable
using drag-and-drop.
Chapter 12: Selection by Drawing a Box
❑
❑ — In Chapter 12, I cover the portion of the jQuery UI
library that lets you make a selection by drawing a box with your mouse, just like you would do
in your OS’s file management application.
Chapter 13: Accordion UI
❑
❑ — In this chapter, I discuss how to make a really neat, polished-looking
sidebar that has panes that transition like an accordion. When you mouse over an element, one
pane collapses via a slick animation, and another one expands, also via an animation.
27794flast.indd 22 3/16/09 11:33:36 AM
Introduction
xxiii
Chapter 14: Datepicker
❑
❑ — In Chapter 14, I cover how you make a standard form input field
into a Datepicker, using jQuery’s Datepicker widget.
Chapter 15: Dialogs
❑
❑ — In Chapter 15, I talk about how you create virtual pop-up windows,
using the jQuery UI library, that look and act like real pop-up windows but are entirely con-
tained in the same web page that launches them and are built using pure markup, CSS, and
JavaScript.
Chapter 16: Tabs
❑
❑ — In Chapter 16, I discuss the jQuery UI tab component, which allows you to
take a document and split it into several tabs and navigate between those tabs without needing
to load another page.
Appendixes
❑
❑ — Appendix A contains the answers to chapter exercises. Appendix B through
Appendix S contain reference materials for jQuery and jQuery UI.
What You Need to Use This Book
To make use of the examples in this book, you need the following:
Several Internet browsers to test your web pages
❑
❑
Text-editing software or your favorite IDE
❑
❑
Designing content for websites requires being able to reach more than one type of audience. Some of
your audience may be using different operating systems or different browsers other than those you have
installed on your computer. This book focuses on the most popular browsers available at the time of this
writing as supported:
Microsoft Internet Explorer 6 or newer for Windows
❑
❑
Safari for Mac OS X, version 2 or newer
❑
❑
Mozilla Firefox for Mac OS X, Windows, or Linux
❑
❑
Opera for Mac OS X, Windows and Linux, version 9 or newer
❑
❑
Conventions
To help you get the most from the text and keep track of what’s happening, I’ve used a number of con-
ventions throughout the book.
First, be aware that not all the figures referenced in the text actually appear in print. This means, for
example, that the screenshots that actually do appear in a chapter might not be numbered in strict
sequence. For example, if you look only at the screenshots in Chapter 3, the first is Figure 3-1, and the
second is Figure 3-3. There is a reference to Figure 3-2 in the text, but the actual screenshot is not printed.
These “missing” screenshots aren’t really missing, though — they are generated by the code download.
It’s just that for all intents and purposes, they are identical to the screenshots that are printed before or
after them and are therefore not needed in the text.
27794flast.indd 23 3/16/09 11:33:36 AM
Introduction
xxiv
Try It Out
The Try It Out is an exercise you should work through, following the text in the book.
1. It usually consists of a set of steps.
2. Each step has a number.
3. Follow the steps through with your copy of the database.
Boxes like this one hold important, not-to-be forgotten information that is directly
relevant to the surrounding text.
Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
As for styles in the text:
We
❑
❑ highlight with italics new terms and important words when we introduce them.
We show keyboard strokes like this:
❑
❑ Ctrl+A.
We show URLs and code within the text like so:
❑
❑ persistence.properties.
We present code in the following way:
❑
❑
We use a monofont type with no highlighting for most code examples.
Also, Visual Studio’s code editor provides a rich color scheme to indicate various parts of code syntax.
That’s a great tool to help you learn language features in the editor and to help prevent mistakes as you
code. To reinforce Visual Studio’s colors, the code listings in this book are colorized using colors similar
to what you would see on screen in Visual Studio working with the book’s code. In order to optimize
print clarity, some colors have a slightly different hue in print from what you see on screen. But all of
the colors for the code in this book should be close enough to the default Visual Studio colors to give
you an accurate representation of the colors.
Source Code
As you work through the examples in this book, you may choose either to type in all the code manually
or to use the source code files that accompany the book. All of the source code used in this book is avail-
able for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the
Search box or by using one of the title lists) and click on the Download Code link on the book’s detail
page to obtain all the source code for the book.
Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is
978-0-470-22779-4.
Once you download the code, just decompress it with your favorite compression tool. Alternatively, you
can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see
the code available for this book and all other Wrox books.
27794flast.indd 24 3/16/09 11:33:36 AM
Introduction
xxv
Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is
perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty
piece of code, we would be very grateful for your feedback. By sending in errata you may save another
reader hours of frustration, and at the same time, you will be helping us provide even higher quality
information.
To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one
of the title lists. Then, on the Book Search Results page, click on the Errata link. On this page, you can
view all errata that have been submitted for this book and posted by Wrox editors.
A complete book list including links to errata is also available at
www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot “your” error on the Errata page, click on the Errata Form link and complete the form to
send us the error you have found. We’ll check the information and, if appropriate, post a message to the
book’s Errata page and fix the problem in subsequent editions of the book.
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based sys-
tem for you to post messages relating to Wrox books and related technologies and interact with other
readers and technology users. The forums offer a subscription feature to e‑mail you topics of interest of
your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts,
and your fellow readers are present on these forums.
At http://p2p.wrox.com, you will find several different forums that will help you not only as you read
this book, but also as you develop your own applications. To join the forums, just follow these steps:
1. Go to p2p.wrox.com and click on the Register link.
2. Read the terms of use and click Agree.
3. Complete the required information to join as well as any optional information you wish to pro-
vide and click Submit.
4. You will receive an e‑mail with information describing how to verify your account and com-
plete the joining process.
You can read messages in the forums without joining P2P, but in order to post your own messages,
you must join.
Once you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the Web. If you would like to have new messages from a particular forum
e‑mailed to you, click on the “Subscribe to this Forum” icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques-
tions about how the forum software works as well as many common questions specific to P2P and Wrox
books. To read the FAQs, click the FAQ link on any P2P page.
27794flast.indd 25 3/16/09 11:33:36 AM
Part I
jQuery API
Chapter 1: Introduction to jQuery
Chapter 2: Selecting and Filtering
Chapter 3: Events
Chapter 4: Manipulating Content and Attributes
Chapter 5: Arrays and Iteration
Chapter 6: CSS
Chapter 7: AJAX
Chapter 8: Effects
Chapter 9: Plugins
1
Introduction to jQuery
JavaScript frameworks have arisen as necessary and useful companions for client-side web devel-
opment. Without JavaScript frameworks, client-side programming becomes a crater-filled mine-
field of cross-browser, cross-platform inconsistencies and idiosyncrasies. JavaScript frameworks
pave over those craters and inconsistencies to create a seamless, enjoyable client-side program-
ming experience.
The most important hole filled by a JavaScript framework is inconsistencies between Internet
Explorer’s and the W3C’s standard Event APIs. jQuery fills in this hole by making a cross-browser
Event API that is very similar to the W3C’s, adding some original helpful extensions of its own.
Another hole filled by most of the popular client-side JavaScript frameworks is the ability to select
and traverse through nodes in the Document Object Model (DOM) using more than the very reme-
dial selection and traversal APIs that are provided by browsers’ default DOM implementations.
jQuery provides a selection mechanism that uses selector syntax like that used in cascading style
sheets. However, not content to support only the standard selectors supported in CSS and even
the new Selectors API implementations supported by WebKit and Internet Explorer 8, jQuery
again extends the standard to support new, innovative, and useful selectors that make sense
when using selectors to select DOM nodes.
In a nutshell, jQuery reduces significantly the amount of JavaScript programming and Q/A (qual-
ity assurance) you have to undertake. It takes what might take several lines of code to write, and
more often than not reduces that to just one or a few lines of code. jQuery makes your JavaScript
more intuitive and easier to understand. jQuery takes JavaScript programming (which at one time
had a higher barrier of entry due to complexity and cross-browser, cross-platform idiosyncrasies)
and makes it easier and more attractive to average web developers.
Throughout this book, I will discuss jQuery’s Application Programming Interface, or API. We’ll
look in depth and up close at each little bit of programming syntax that enables jQuery to do what
it does. With each new bit, I also provide simple, to-the-point examples that demonstrate how that
bit works. I show you how to write JavaScript applications using jQuery, and by the end of this
book, you too will be able to create Web 2.0 applications that function seamlessly across multiple
browsers and platforms.
4
Part I: jQuery API
In this chapter, I begin discussion of jQuery by introducing what you get out of jQuery, who develops
jQuery, how you obtain jQuery, and how you install jQuery and test that it is ready to use.
As I mentioned in the Introduction, I do not assume that you are a JavaScript expert in this book, but I
do assume that you are familiar with basic JavaScript concepts, such as the DOM and attaching events.
I will do my best to keep examples simple and to the point and avoid layering on thick programming
jargon.
What Does jQuery Do for Me?
jQuery makes many tasks easier. Its simplistic, comprehensive API has the ability to completely change
the way you write JavaScript, with the aim of consolidating and eliminating as many common and
redundant tasks as possible. jQuery really shines in the following areas:
jQuery makes iterating and traversing the DOM much easier via its various built-in methods for
❑
❑
doing the same.
jQuery makes selecting items from the DOM easier via its sophisticated, built-in ability to use
❑
❑
selectors, just like you would use in CSS.
jQuery makes it really easy to add your own custom methods via its simple-to-understand
❑
❑
plug-in architecture.
jQuery helps reduce redundancy in navigation and UI functionality, like tabs, CSS and markup-
❑
❑
based pop-up dialogues, animations, and transitions, and lots of other things.
jQuery won’t do your laundry, walk the dog, or broker world peace (yet), but it does bring a lot to the
table in terms of making client-side website development easier.
Is jQuery the only JavaScript framework? — no, certainly not. You can pick from several JavaScript
frameworks: base2, Yahoo UI, Prototype, SproutCore, Dojo, and so on. I picked jQuery for this book
simply because I enjoy its simplicity and lack of verbosity. On the other hand, among the other frame-
works, you’ll find that there is a lot of similarity and each provides its own advantages in terms of uni-
fying Event APIs, providing sophisticated selector and traversal implementations, and providing
simple interfaces for redundant JavaScript-driven UI tasks.
In the past, I’ve been a big fan of base2, simply for its commitment to supporting W3C-sanctioned and
de facto standard APIs seamlessly. But I have decided to focus on jQuery exclusively and exhaustively
for this book because I think its popularity merits comprehensive coverage, which I’m able to present in
a way that is more befitting novice programmers.
In a nutshell, jQuery blurs and even erases lines in some places that existed as barriers for true cross-
browser, cross-platform development. It gives you a standard Event API, a standard Selectors API, use-
ful traversal and enumeration methods, and a very useful UI library that work across the board in
Internet Explorer, Safari, Firefox, and Opera on Windows, Mac, and Linux platforms.
That’s not to say that you won’t ever encounter cross-browser issues with your programs, but jQuery
makes it much less likely and eliminates a hefty chunk of compatibility issues.
5
Chapter 1: Introduction to jQuery
Who Develops jQuery?
I won’t spend a lot of time talking about the history of JavaScript frameworks, why they exist, and so on.
I prefer to get straight to the point. That said, a brief mention of the people involved with developing
jQuery is in order.
jQuery’s lead developer and creator is John Resig, whose website is located at www.ejohn.org. John
resides in Boston, Massachusetts and is a JavaScript Evangelist for the Mozilla Corporation.
There are also several other people who have contributed to jQuery and continue to assist with its
development. You can learn more about these people and what roles they played in jQuery’s develop-
ment at http://docs.jquery.com/About/Contributors.
Obtaining jQuery
jQuery is a free, Open Source JavaScript Framework. The current stable, production release version, as
of this writing, is 1.2.6. I use version 1.2.6 throughout the course of this book. Getting jQuery is easy —
all you have to do is go to www.jquery.com and click on the “Download” link. You’ll see three options
for downloading: a packed and gzipped version, an uncompressed version, and a packed version; these
all refer to the same jQuery script. Download “uncompressed” if you want to be able to look at jQuery’s
source code. Download “packed” if you, for whatever reason, are unable to use gzip compression. The
packed version is the same JavaScript code minus all comments, white space, and line breaks. Otherwise,
for the best possible download performance, the packed and gzipped version is the best.
Installing jQuery
Throughout this book, I will refer to the jQuery script as though it is installed at the following path:
www.example.com/Library/jquery/jquery.js.
Therefore, if I were using the domain example.com, jQuery would have this path from the document
root, /Source Code/jquery/jquery.js. You do not have to install jQuery at this exact path.
The following “Try It Out” assists you with installing jQuery by giving you an alternative dialogue
when the script is properly installed.
Try It Out Installing and Testing jQuery
Example 1-1
To install and test jQuery, follow these steps.
1. Download the jQuery script from www.jquery.com. Alternatively, I have also provided the jQuery
script in this book’s source code download materials available for free from www.wrox.com.
2. Enter the following XHTML document, and save the document as Example 1-1.html. Adjust your
path to jQuery appropriately; the path that I use reflects the path needed for the example to
6
Part I: jQuery API
work when opened in a browser via the source code materials download made available for
this book from www.wrox.com.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd”>
<html xmlns=’http://www.w3.org/1999/xhtml’ xml:lang=’en’>
<head>
<meta http-equiv=’content-type’ content=’text/html; charset=utf-8’ />
<meta http-equiv=’content-language’ content=’en-us’ />
<title>Link</title>
<script type=’text/javascript’
src=’../../../Source Code/jQuery/jQuery.js’>
</script>
<script type=’text/javascript’ src=’Example 1-1.js’></script>
<link type=’text/css’ href=’Example 1-1.css’ rel=’stylesheet’ />
</head>
<body>
<p>
jQuery is not loaded.
</p>
</body>
</html>
3. Enter the following JavaScript document, and save the document as Example 1-1.js:
if ($) {
$(document).ready(
function() {
$(‘p’).addClass(‘tmpFrameworkLoaded’);
$(‘p’).text(‘jQuery successfully loaded and running!’);
}
);
}
4. Enter the following CSS document, and save the document as Example 1-1.css:
body {
font: 16px sans-serif;
}
p {
color: red;
border: 1px solid red;
padding: 5px;
margin: 5px;
}
p.tmpFrameworkLoaded {
color: green;
border: 1px solid green;
}
The preceding code results in the screenshot that you see in Figure 1-1, if the installation was unsuc-
cessful; and the screenshot in Figure 1-2, if the installation was successful.
7
Chapter 1: Introduction to jQuery
Figure 1-1
Figure 1-2
In the preceding example, you installed and tested your installation of the jQuery framework. The
XHTML document references a style sheet and a test JavaScript. The XHTML document contains just a
single <p> element that contains the text “jQuery is not loaded.” The style sheet has a rule that makes
that text red with a red border around the <p> element.
The JavaScript that you included first looks for the jQuery object, which is contained in a single dollar
sign. That one dollar sign contains all of jQuery’s functionality, which makes jQuery statements really
short. If that’s too short for you, you can also substitute “jQuery” for the dollar sign, which would have
made that JavaScript example look like this:
if (jQuery) {
jQuery(document).ready(
function() {
jQuery(‘p’).addClass(‘tmpFrameworkLoaded’);
jQuery(‘p’).text(‘jQuery successfully loaded and running!’);
}
);
}
8
Part I: jQuery API
An event is attached to jQuery’s ready event, which is executed as soon as the DOM is fully loaded, or
all markup content, JavaScript and CSS, but not images. In old-time JavaScript, you would have made
your JavaScript execute at page load, or the onload event. The onload event can be much slower, how-
ever, since it waits for all content and images to load before executing, instead of just content.
With an event attached to the ready event, you’re ready to do something with the document. In this
case, once the document is loaded, jQuery selects the <p> element and gives it the class name
tmpFramework​
Loaded. Then jQuery selects the <p> element again and changes its text content to say
“jQuery successfully loaded and running!” The addition of the class name results in the <p> element
having green text with a green border around the element.
The preceding is a pretty simple, cut-and-dry test of jQuery’s existence, and with this simple example,
you see a huge difference with traditional, framework-less JavaScript. Without the jQuery framework,
this is what the preceding example would have looked like:
window.onload = function() {
var $p = document.getElementsByTagName(‘p’)[0];
$p.className = ‘tmpFrameworkLoaded’;
if ($p.innerText) {
$p.innerText = ‘jQuery successfully loaded and running!’;
} else {
$p.textContent = ‘jQuery successfully loaded and running!’;
}
};
Programming Conventions
In web development, it’s common for professional web designers, web developers — and anyone with
a job title whose day-to-day activities encompass the maintenance of source code — to adopt standards
and conventions with regard to how the source code is written. Standardization bodies like the W3C, who
define the languages that you use to create websites, already decide on some standards for you. Some
standards are not written, but are rather de facto standards. De facto standards are standards that have
become accepted throughout the industry, despite not appearing in any official document developed by
a standards organization.
Throughout this book, I talk about standards, de facto and official, and how to develop and design web-
based documents and even web-based applications that take those standards into account. For example,
I talk extensively about how to separate behavior (JavaScript) from presentation (CSS) and structure
(XHTML). JavaScript written in this way is commonly referred to as non-intrusive JavaScript — it’s non-
intrusive because it supplements the content of a web document, and, were it turned off, the document
would still be functional. CSS is used to handle all the presentational aspects of the document. And the
structure of the document lives in semantically written XHTML. XHTML that is semantically written is
organized meaningfully with the right markup elements and contains very little, if any at all, presenta-
tional components directly in the markup.
9
Chapter 1: Introduction to jQuery
In addition to standards, I discuss how to develop web-based documents, taking into account different
browser inconsistencies, discrepancies, and idiosyncrasies. There is some interactive functionality that
nearly every browser handles differently; in those situations, other web professionals have already pio-
neered de facto standards that are used to bring all browsers into accord. The idea of a JavaScript foun-
dational framework has become more popular and increasingly a dependency for so-called Web 2.0
applications, like the ones you’ll learn to develop using the jQuery framework.
Before I begin the discussion of jQuery, in the coming sections, I provide a generalized overview of pro-
gramming conventions and good practice that should be followed.
XHTML and CSS Conventions
It’s important that your web documents be well-organized, cleanly written, and appropriately named
and stored. This requires discipline and even an obsessive attention to the tiniest of details.
The following is a list of rules to abide by when creating XHTML and CSS documents:
Catch errors in XHTML and CSS.
❑
❑
When selecting ID and Class names, make sure that they are descriptive and are contained in a
❑
❑
namespace. You never know when you might need to combine one project with another — name­
spaces will help you to prevent conflicts.
When defining CSS, avoid using generic type selectors. Make your CSS more specific. This will
❑
❑
also help with preventing conflicts.
Organize your files in a coherent manner. Group files from the same project in the same folder;
❑
❑
separate multiple projects with multiple folders. Avoid creating huge file dumps that make it
difficult to locate and associate files.
Avoid inaccessible markup. Stay away from frames, where possible. Organize your markup
❑
❑
using semantically appropriate elements. Place paragraphs in <p> elements. Place lists in <ul>
or <ol> elements. Use <h1> through <h6> for headings, and so on.
If you are able to, also consider the loading efficiency of your documents. For development, use
❑
❑
small, modularized files organized by the component; combine and compress those modular-
ized files for a live production site.
In the following sections, I present some examples of why the preceding list of rules is important.
Catching Errors in XHTML and CSS
There are certain times when you won’t be able to easily spot markup or style errors. More often than
not, getting into a routine of indenting and spacing markup documents and style sheets will make it
much easier to spot errors during the initial development of a document, and much easier to perform
ongoing maintenance. However, neat and tidy development of a document isn’t always an option.
Maybe you’ve inherited an old content management system or have to deal with some other piece of
software that generates your source code for you. Next I’ll talk about what you can do to more easily
detect and repair errors.
10
Part I: jQuery API
Markup Errors in XHTML and HTML
Markup errors typically come about from simple human error. You may forget to type in a closing tag
for an element. You may forget to encode certain special characters. You may use an ID name more than
once in a document by mistake.
If a web document contains errors, the browser may carry on as if everything is just fine and dandy,
and it may not be obvious that it contains errors. Some errors go undetected because browsers are
designed to handle errors in HTML as they are found. The browser decides what to do with an error
when it comes to it and then simply moves on with processing the HTML document. (For example, it
may be able to guess where a closing tag is supposed to be.) When an error is found, the browser tries
to continue on and display a document to the end-user, and more often than not, it succeeds.
In some cases, you may notice a visual glitch and see clearly that something is out of place, but it’s also
possible that something not so obvious has been affected by the error. For example, you may try attach-
ing an event with JavaScript, and the event doesn’t fire. You may try manipulating the document with
script by removing or inserting elements and find that the elements aren’t being inserted, or are being
inserted in the wrong place. The effects of markup errors like this are much more subtle. Markup errors
do not appear in your browser’s error console. The only place where a structural markup error will
show up is in a validation of the document using the W3C’s markup validation service located at
http://validator.w3.org.
XHTML, on the other hand, is not forgiving of markup errors, and assuming that the browser properly
supports XHTML, the browser won’t attempt any kind of error correction when it encounters an error
in an XHTML document. One type of markup error that will bring processing to a halt is an incorrectly
specified MIME (Multipurpose Internet Mail Extensions) type.
The MIME standard is used by browsers and Web Servers to facilitate the automatic identification and
handling of files, which is to say that a MIME type is part of what a browser uses to identify the con-
tents of a document. XHTML documents are supposed to be served with an application/xhtml+xml
MIME type. The following is one way of setting the MIME type for an XHTML document:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=’http://www.w3.org/1999/xhtml’ xml:lang=’en’>
<head>
<meta http-equiv=’Content-Type’
content=’application/xhtml+xml; charset=UTF-8’ />
</head>
<body>
In the preceding code example, the XHTML MIME type is set using a <meta /> element that’s included
in the document headers. The http-equiv attribute included in a <meta /> element is used to set HTTP
headers within the markup document itself. In the preceding code example, the Content-Type HTTP
header is being set, which, when supported by the browser, will force the browser to interpret an
XHTML document as application/xhtml+xml, rather than text/html.
An XHTML document properly served with the application/xhtml+xml MIME type with markup errors
like mismatched tags, or missing tags, or any markup error of any kind will result in what’s commonly
called the XML yellow screen of death (YSOD). The name yellow screen of death was coined because Mozilla’s
(and later, Firefox’s) XML error messages appear against a yellow background, and XML error messages
11
Chapter 1: Introduction to jQuery
prevent the display of the document, which prevents the user from seeing a web page, hence the “death”
part. Of course, the XML/XHTML error message isn’t yellow in every browser, but the point is that, in
properly served XHTML, one error could make a document unviewable by the end-user.
The yellow screen of death is also related to another error message, the blue screen of death, which, of
course, is the de facto name for error messages in the Windows Operating System that result in a complete
system crash — at the time of the crash, an error message with white lettering on a blue screen is seen.
XHTML 1.0 documents are not typically served with the correct, intended MIME
type. Rather, they are usually served as an HTML document — which isn’t techni-
cally illegal, as long as they are XHTML 1.0 documents. XHTML 1.1, on the other
hand, must be served as application/xhtml+xml.
It’s a good idea, if you’re going the XHTML route, to properly serve the document with the
application/xhtml+xml MIME type. Setting the XHTML MIME type is the best, most compatible
approach, since browsers like IE that don’t understand the XHTML MIME type will carry on and inter-
pret the document as plain-old HTML, while Firefox, Safari, and the like will correctly interpret the
XHTML document. If errors are present, these browsers won’t show a rendered document but, rather,
will show an error message complaining that something is awry in the document.
If you’re going the XHTML route, keeping the document neat becomes a matter of keeping the document
maintainable, and thus a matter of personal preference. Typically, dynamic websites strip the markup
source of excess white space in order to reduce the size of the document for performance advantages,
and even in the age of ubiquitous broadband connections, it’s still a good idea to optimize a document
for very slow dial-up connections, which are still in widespread use in rural areas. Dynamic websites
typically also have the best of both worlds in place. That is to say, on a pre-production server, the website
may serve uncompressed markup, while on a production server, the website serves compressed markup.
For your own sanity as a programmer, I strongly recommend that you maintain neat and organized
markup, check your markup documents for validation errors using the W3C validation service, and
consider using XHTML. Ultimately, however, XHTML or HTML is a matter of personal preference.
Both are perfectly acceptable Internet standards for the creation of web documents. The examples in
this book use the XHTML standard — however, these examples will work equally well with the HTML
standard.
Errors in CSS
Errors in style sheets usually make themselves known by not displaying the style you applied.
However, errors in CSS can also be more subtle and difficult to spot. To catch errors in CSS, I recom-
mend one of the two following approaches:
Use Mozilla Firefox (or another browser that reports CSS errors), and look for CSS errors in the
❑
❑
browser’s Error Console. In Firefox, that’s located in Tools?Error Console.
Use the W3C’s CSS validation service at
❑
❑ http://jigsaw.w3.org/css-validator.
Either of these solutions will assist you in locating and extinguishing style-sheet errors.
12
Part I: jQuery API
It’s also good practice to get into the habit of writing neat and organized CSS. Indent your style sheets
with white space, and use line breaks to make the style sheets more maintainable. The browser doesn’t
care what your style sheet looks like, as long as the basic syntax is correct. You may add or remove
white space to your heart’s content.
I continue to revisit the topics of neat and organized source code throughout this book by way of example.
ID and Class Naming Conventions
Most web developers don’t think too much about the topics of namespacing and naming conventions.
Naming conventions are just as important in your markup ID and class names as namespacing is impor-
tant in programming languages.
First, what is namespacing, and why do you need to do it? Namespacing is the concept of making your
programs, source code, and so on tailored to a particular naming convention, in an effort to make your
programs more portable and more capable of living in diverse, foreign programming environments. In
other words, if you want to be able to directly insert a web application into your document, you want to
be sure that the class and ID names, style sheets and script, and all the bits that make your web applica-
tion what it is do not conflict with any applications that are already present in the document. Your appli-
cations should be fully self-contained and self-sufficient and not collide or conflict with any elements
already present in a document.
What are some common ID names that people use in style sheets? Think first about what the typical
components of a web application are. There’s a body. There may be one or more columns. There may be
a header and a footer, and there are lots of components that can potentially be identified as generic,
redundant pieces that all web applications may have. Then, it stands to reason that plenty of websites
are probably using ID and class names like body, header, footer, column, left, right, and the like. If you
name an element with the ID or class name body, you have a very good chance of conflicting with an
overwhelming majority of websites in existence today. To avoid this type of conflict, it’s considered
good practice to prefix ID and class names within a web application to avoid conflicts and namespace
collisions. If you write an application called tagger, you might namespace that application by prefixing
all of your ID and class names with the word tagger. For example, you might have taggerBody, tagger​
Header,
taggerFooter, and so on. It may be possible, however, that someone has already written an application
called tagger. To be safe, you might do a Web search on the name you’ve chosen for your application to
make sure that no one’s already using that name. Typically, simply prefixing your ID and class names
with your application’s name is enough.
Additionally, it also helps to prefix ID and class names with type selectors in style sheets. Type selectors
help you narrow down what to look for when modifying or maintaining a document. For example, the
ID selector #thisID is ambiguous. You don’t know what kind of element thisID is, and thus would likely
have to scan the entire document to find it. But div#thisID is more specific. By including the div in the
selector, you instantly know you’re looking for a <div> element. Including the type in the selector also
helps you in another way: When dealing with class names, you can have the same class name applied to
different types of elements. While I may not condone that as good practice, at least in the style sheet, you
can control which element gets which style. span.someClass and div.someClass are selectors that dif-
ferentiate style based on the type of element, whereas .someClass is more ambiguous and applies to
any element.
ID and class names should also be descriptive of their purpose in a semantically meaningful way.
Keep in mind that an ID name can potentially be used in a URL as an HTML anchor. Which is better:
13
Chapter 1: Introduction to jQuery
www.example.com/index.html#left or www.example.com/index.html#exRelatedDocuments? The lat-
ter ID anchor is namespaced ex for example.com, and RelatedDocuments is the name of the element;
thus, the latter URL includes more information about what purpose the element serves and greatly
increases the maintainability of the document in a very intuitive way. Additionally, the latter has more
benefit in terms of search engine optimization (SEO). The former is too ambiguous and won’t provide
much in the way of SEO. Think of each of your ID and class names as though it is part of the URL of
your document. Give each ID and class name that you create semantic names that convey meaning and
purpose.
Generic Type Selectors
Generic type selectors are style-sheet rules that look something like this:
a {
color: #29629E;
}
In the preceding style-sheet rule, you see what’s probably a pretty common scenario, changing the color
of every link in a document via a generic type selector that refers to all <a> elements. Generic type selec-
tors should be avoided for the same reason that it is good to namespace ID and class names within a
document, avoiding conflicts when multiple scripts or style sheets are combined in the same document.
Instead, it’s best practice to apply ID or class names to these elements, or at the very least, place them in
a container that has an ID or class name, and only use descendent selectors when referencing those ele-
ments via a style sheet.
div#tmpBanner a {
color: #29629E;
}
The preceding example avoids the pitfalls introduced by using a blanket, generic selector style-sheet
rule by limiting the scope of the style-sheet rule’s application. Now, only <a> elements that are descen-
dants of a <div> with the ID name tmpBanner will receive the declaration color: #29629E;.
Storing and Organizing Files
How files are organized and stored is important to the maintainability of a document. You should main-
tain your documents in an easy-to-understand, easy-to-learn directory hierarchy. Different people have
different approaches to storing and organizing files, obviously. What matters is that there is an organiza-
tion scheme, rather than none at all. Some choose to store documents by type and then separate them by
application, while others prefer to separate by application first, then sort by type.
Avoid Making Documents Inaccessible
Accessibility is also an important factor to consider in the design of a web document. You should do
your best to make your JavaScript non-intrusive, but also avoid taking away a document’s accessibility
by either script or markup.
Avoid using frames.
❑
❑
Limit the number of images to those that actually contribute to the content of a document (as
❑
❑
opposed to the design). Try to contain as much of the design as possible in CSS background
14
Part I: jQuery API
images, and keep images that contribute to the content in <img /> elements. Be sure to include
alt attributes that describe the image for each <img /> element.
Place content in semantically appropriate markup containers — use
❑
❑ <p> for paragraphs, <h1>
through <h6> for headings, for example.
Make the design high contrast. Imagine what the document would look like in black and white
❑
❑
through the eyes of someone with poor vision. Can you easily read the content?
Avoid wandering too far away from established user-interface conventions. Can you distinguish
❑
❑
hyperlinks from normal content?
Make the content keyboard-accessible. Can you navigate without a pointing device?
❑
❑
Make the content unobtrusive. Can you use the website without flash and JavaScript functional-
❑
❑
ity? JavaScript and flash should enhance web content in a complementary way, not be a
requirement.
Avoid placing a large number of links at the beginning of every document. If you were listening
❑
❑
to the content being read to you, rather than seeing it visually, would the experience be enjoyable?
Accessibility should be practiced to the point of becoming an automatic reflex. It should be cemented in
your development practices in a fundamental way in the same way that namespacing, file organization,
and validation are; but while other best practices can become second nature easily, it’s also very easy to
get into the habit of ignoring accessibility, so a conscious effort must be made to periodically review
accessibility and ingrain accessibility in the development process.
Efficiency in Markup and CSS
Markup and CSS in a complex website can easily become large and bloated and drag down overall load-
ing and execution times more and more. This can become particularly troublesome as the overall popu-
larity of a site increases. As the complexity of a website increases, it becomes necessary to look into ways
of streamlining the content. It’s best to limit the number of external files being loaded, but all CSS and
JavaScript should be included in at least one external file. Were JavaScript and CSS included directly in a
document, the initial loading time would improve, but you’d also lose the advantage of caching JavaScript
and CSS on the client side.
For the best of the best in efficiency, combine the following concepts:
Server-side gzip compression
❑
❑
Client-side caching
❑
❑
Automatic compression of markup content
❑
❑
Automatic compression and consolidation of multiple CSS and JavaScript files
❑
❑
When the preceding items are combined, you make the loading times of a web document the best pos-
sible; however, there are some caveats to consider that may at first seem contradictory:
Maintainable markup should be written in a neat and organized manner. It should be well-
❑
❑
spaced and indented and contain line breaks where appropriate.
Good programming practice means modularized development, so break up your CSS and
❑
❑
JavaScript by component and application. Make small, easy-to-digest chunks. This will speed
up your ability to maintain and extend projects.
15
Chapter 1: Introduction to jQuery
Client-side caching can lead to headaches when updates are made to CSS or script files.
❑
❑
Browsers will continue to use the old version of the CSS and script files after an update is made,
when caching is working correctly.
The good news is, all of the preceding caveats can be overcome. The bad news is, it’s not particularly
easy to overcome them.
The best way to implement efficiency in markup, JavaScript, and CSS documents is to make the effi-
ciency automatic. That is to say, write server-side applications that handle efficiency tasks for you. A
well-designed professional content management system will work out those bits for you. It will allow
you to make your JavaScript, markup, and CSS documents modularized, and separate them based on
the task each is designed to perform, but automatically combine and compress those documents for you.
Unfortunately, not everyone can use a professional content management system to serve their content.
For those individuals, there are some compromises to be made:
JavaScript and CSS can be hand-compressed using a web-based utility like Dean Edwards’s
❑
❑
packer, http://dean.edwards.name/packer. Development can continue to be modularized,
and the compression and consolidation portion of development simply becomes a manual task.
You can limit the amount of white space you use in a document. Indent content with two spaces
❑
❑
instead of four.
Overcoming the headaches with document caching, on the other hand, is a much easier task. You can
force a browser to update a document by changing its path. For example, say you have the following
script included in your markup:
<script src=’/script/my.js’ type=’text/javascript’></script>
You change the path from /script/my.js to /script/my.js?lastModified=09/16/07. The latter references the
same, my.js, but is technically a different path to the browser and, consequently, will force the browser
into refreshing its cached copy of the document. The ?lastModified=09/16/07 portion of the path is what’s
called the query string portion of the path. The query string begins with a question mark and then con-
tains one or more query string variables. Query string variables are used by a server-side programming
language or client-side JavaScript to pass information from one document to another. In this example,
there is no information being passed per se. You’re including the time of the last modification, although
I could have just as easily included the revision, or even a random string of characters. The inclusion of
a query string in this example has only one purpose: to force the browser into refreshing the cached
version of the document.
The same can be done with CSS:
<link type=’text/css’ rel=’stylesheet’ href=’/styles/my.css?lastModified=09/16/07’ />
In the preceding snippet of markup that includes an external CSS document, the query string is used to
force a refresh of the browser’s cached copy of the style sheet my.css.
In the next section, I talk about some conventions specific to JavaScript.
16
Part I: jQuery API
JavaScript Conventions
In JavaScript, there are several things that should be considered bad practice and avoided:
Include All Script in External Documents
❑
❑ — JavaScript code should only be included in exter-
nal script files. Script should not be embedded in markup documents or be included inline,
directly on markup elements.
Write Clean, Consistent Code
❑
❑ — JavaScript code should be neatly formatted and organized in a
consistent, predicable way.
Namespace JavaScript Code
❑
❑ — JavaScript variables, functions, objects, and the like should be
namespaced to minimize potential namespace conflicts and collisions with other JavaScript
applications.
Avoid Browser Detection
❑
❑ — Browser detection should be avoided where possible. Instead,
detect specific browser features.
In the next sections, I present cursory, generalized overviews of each of the preceding concepts.
Include All Script in External Documents
Part of making JavaScript non-obtrusive means making JavaScript complementary and supplemental,
rather than required and mandatory. This concept is explored in detail throughout this book; however,
it should be noted why this is the best approach.
Consider the following code example:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”vvvvvv
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type”
content=”application/xhtml+xml; charset=UTF-8”/>
<title>Inline JavaScript</title>
<link rel=’stylesheet’ type=’text/css’ href=’style.css’ />
</head>
<body>
<p>
<img src=’pumpkin.jpg’ alt=’Pumpkin’ />
<a href=’javascript:void(0);’
onclick=’window.open(
“pumpkin.jpg”,
“picture”,
“scrollbars=no,width=300,height=280,resizable=yes”
);’>Open Picture</a>
</p>
</body>
</html>
Combine the preceding markup with the following style sheet:
img {
display: block;
17
Chapter 1: Introduction to jQuery
margin: 10px auto;
width: 100px;
border: 1px solid rgb(128, 128, 128);
}
body {
font: 14px sans-serif;
}
p {
width: 150px;
text-align: center;
}
The preceding code gives you something like what you see in Figure 1-1.
In Figure 1-1, you see what is probably a pretty common scenario: You have a thumbnail, and you can
click to see a bigger version of the thumbnail. This is the kind of thing that JavaScript works well for
— giving you the bigger version in a separate pop-up window that doesn’t have any controls.
Now let’s examine why what I did in Figure 1-1 was the wrong way to go about adding this
functionality.
Here are the problems with this approach:
If JavaScript is disabled, viewing the larger picture doesn’t work.
❑
❑
JavaScript can be disabled out of personal preference.
❑
❑
JavaScript can be disabled because of company policy.
❑
❑
JavaScript can be disabled if the end-user is using a handheld device or viewing the site
❑
❑
through any kind of alternative medium.
Search bots may not understand the JavaScript, so Search Engines may not properly index this
❑
❑
content.
Placing the JavaScript directly in the markup document adds unnecessary bloat and complexity
❑
❑
to the markup document.
The overwhelming point in all of this is that inline JavaScript is a really bad way to approach adding
complementary, interactive functionality to a web document.
Here is a better approach to the application presented in Figure 1-1. First, you take the inline JavaScript
out of the markup and replace it with a reference to an externally loaded JavaScript. In the following
example, I’ve named the externally loaded JavaScript thumb.js:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<meta http-equiv=”Content-Type”
content=”application/xhtml+xml; charset=UTF-8”/>
<title>Inline JavaScript</title>
<link rel=’stylesheet’ type=’text/css’ href=’style.css’ />
<script type=’text/javascript’ src=’thumb.js’></script>
18
Part I: jQuery API
</head>
<body>
<p>
<img src=’pumpkin.jpg’ alt=’Pumpkin’ />
<a href=’pumpkin.jpg’>Open Picture</a>
</p>
</body>
</html>
Then in the externally loaded JavaScript you do something like the following:
window.onload = function()
{
var $nodes = document.getElementsByTagName(‘a’);
for (var $i = 0, $length = $nodes.length; $i < $length; $i++) {
$nodes[$i].onclick = function($e) {
window.open(
this.href,
“picture”,
“scrollbars=no,width=300,height=280,resizable=yes”
);
$e? $e.preventDefault() : (window.event.returnValue = false);
};
}
};
With the preceding bits of code, you get the same results that you saw in Figure 1-1, and an example of
non-obtrusive JavaScript. Non-obtrusive JavaScript provides extended, interactive functionality within
a web document, but does not do so in a way that obstructs using the document in a plain-vanilla man-
ner. That is to say, with JavaScript disabled, you are still able to use the website and get what you need
from it.
In the preceding example, the JavaScript is moved to an external document called thumb.js. thumb.js gets
all <a> elements present in the document with document.getElementsByTagName(‘a’). Each <a> ele-
ment is placed in an array called $nodes, and then a for loop is used to iterate through every <a> element
present in the $nodes variable. This is done by making a counter, variable $i; then the number of <a>
elements is assigned to a variable called $length via the $nodes.length property. Now the for loop will
execute once for every <a> element present, and the variable $i will increment by a count of 1 each time.
When the variable $i contains a count that’s more than the number of <a> elements, execution of the
for loop will end.
Inside the for loop, you have an onclick event that’s assigned to each <a> element present in the $nodes
array. An anonymous function is assigned to the onclick event. When a user clicks on an <a> element,
the anonymous function will be executed. Within the anonymous function, the <a> element’s proper-
ties are available in a special object called this. You see a call to the window.open method; the href prop-
erty of the <a> element is passed as the path to open in the new window (this.href), then the window
name and some window parameters are defined.
So far, the user clicks on an <a> element and gets a pop-up window. You want the window to pop up
instead of initiating the default action that occurs when a user clicks on a link (which is for the browser
to navigate to the document defined in the href attribute of the <a> element). Stopping the default
19
Chapter 1: Introduction to jQuery
action, unfortunately, depends on what browser you’re using. IE has its way, and all the others have a
standard way. The JavaScript code accounts for both in the following line:
$e? $e.preventDefault() : (window.event.returnValue = false);
The preceding line says that if the variable $e evaluates to a Boolean true value, execute the
prevent​
Default method of the event object, as in, $e.preventDefault();, otherwise, if $e evaluates
to a false value, evaluate this expression: (window.event.returnValue = false). So if $e is true, use
the standard W3C method for preventing the default action; if $e is false, use Microsoft’s method for
preventing the default action.
In this very simple example, you’ve seen how a really simple example can balloon into something much
more complex. All of the concepts I’ve presented in this example are ones I continue to revisit through-
out this book, but you get a pretty good idea of some of the challenges that non-obtrusive JavaScript
prevents. You run into situations in which one browser has one way of doing things, and another has its
way of doing things, and sometimes all of the popular browsers differ on how to go about accomplish-
ing a given task. Therefore, doing JavaScript the right way often involves quite a bit more thought and
planning. The good thing about this additional thought and planning is that it becomes second nature
once you understand how to account for all of the browser differences. The good news is that there are
people out there looking out for you, and who’ve already braved all the deep, dark corners of browser
inconsistencies, incompatibilities, and lack of common, coherent standards.
At this point, you might be asking yourself, so what are the benefits of going through all of this hassle
to get non-obtrusive, multiplatform JavaScript? I’m glad you asked.
In the preceding example, if JavaScript had been disabled, the end-user could still have clicked
❑
❑
on the link to see a larger version of the thumbnail image. This makes your website much more
accessible.
When JavaScript is included in an externally loaded file, you get a speed boost, since the
❑
❑
JavaScript only has to be loaded once, and from there on is cached by the client browser.
While it takes some planning, the cross-browser inconsistencies and incompatibilities can be
❑
❑
completely overcome.
You can achieve better search rankings, since search engines can now access and see all of your
❑
❑
content.
You’ll appear more hip, all the girls (or guys) will like you, a pretty butterfly will land on your
❑
❑
shoulder, there will be world peace, and so on.
Well, maybe not that last one, but non-obtrusive JavaScript is, simply, A Good Thing™.
Write Clean, Consistent Code
It’s important to follow some predetermined criteria for producing clean, consistent, well-organized
code. In the professional world, most programmers have a particular way they like to see their code for-
matted. Earlier in this section, I talked about how indenting and spacing markup and CSS documents
can help you more easily catch errors in those documents and make those documents more maintain-
able. Well, the same can be applied to JavaScript, although, with JavaScript and other programming lan-
guages, programming conventions are typically much more defined, down to a very fine-grained level
of detail. Here I talk about each of the programming conventions that I follow for writing JavaScript
source code.
20
Part I: jQuery API
Indenting and Line Length
It’s a good idea to indent your code so that it’s easier to read and maintain. Take the following, for
example:
window.onload=function(){var $nodes=document.getElementsByTagName(‘a’);
for(var $i=0,$length=$nodes.length;$i<$length;$i++){$nodes[$i].onclick=function($e){
window.open(this.href,”picture”,”scrollbars=no,width=300,height=280,resizable=yes”);
$e? $e.preventDefault():(window.event.returnValue=false);};}};
In the preceding block of code, you see the contents of thumb.js presented above in this section, format-
ted without any indenting or spacing. Now, imagine that the preceding code is 10,000 lines of code
spread out over many files, all formatted the same way. It’s not a bad idea to reduce spacing for a live,
production script; in fact, many professionals use compression routines specifically for this. But those
same professionals don’t maintain their scripts in the compressed format and often have a rigid pro-
gramming standard to which every script they produce must conform.
A common, fairly universal programming standard is setting the size of an indentation to four spaces,
although some use just two spaces. This is in addition to setting a blanket rule that tabs cannot be used
in place of individual spaces, even though, technically, a tab character results in less bytes added to a
file when compared to four individual space characters. The “no tab” rule exists because of the wide
variance in the interpretation of what a tab character is in text applications. Some text applications say
that a tab character is equal to eight individual spaces. Some text applications say that a tab character is
equal to four individual spaces, while others still let you explicitly define how big a tab character is.
These variances have led to the tab character being unreliable. Most professional integrated developer
environments (IDEs) let you define the [Tab] key on a keyboard as individual spaces, in addition to let-
ting you define how many spaces to insert.
Some examples of IDEs are Adobe Dreamweaver, Zend Studio, and Microsoft Visual Studio: These are
all development environments for either directly writing or generating source code. Additionally, most
IDEs try to guess what you mean when writing a source document, by intelligently adjusting the num-
ber of spaces. For example, when you press [Return] to begin a new line in your source code document,
the IDE can indent the new line with at least as much space as the preceding line. Most IDEs behave
this way by default. Dreamweaver automatically inserts two spaces when you hit the [Tab] key. Zend
Studio can be configured to insert spaces instead of tab characters when you press the [Tab] key.
Throughout this book, I try to use four characters for a [Tab] key, although limited space may sometimes
require that I use two characters. Generally, the professional standard for client-side source code is two
characters, since four characters makes file sizes much larger. I’ve stuck with four because concerns about
file size and bandwidth usage can be addressed by compressing your source code when it’s used on a
production website.
Control Structures
Control structures include programming statements that begin with the keywords if, if else, switch, case,
else, for, while, try, catch, and the like. Control structure programming statements are the building blocks
of any programming language. Let’s see how control structure statements should be formatted with
regard to popular programming standards and guidelines.
21
Chapter 1: Introduction to jQuery
Although, ultimately, different people have different preferences for how to write source code, there are
two prevailing methods for formatting control structures in use by the majority of the professional pro-
gramming community.
The following convention, which is formally called K&R Style, is included in Sun’s Coding Standards
Guidelines for Java:
if ($condition) {
$something = 1;
} else if ($another) {
$something = 2;
} else {
$something = 3;
}
In the preceding code example, you see that the curly braces and the parentheses are used as markers
for indention.
Compare the preceding to the next convention, which is known as Allman Style, which is the default in
Microsoft Visual Studio:
if ($condition)
{
$something = 1;
}
else if ($another)
{
$something = 2;
}
else
{
$something = 3;
}
In Allman Style, all the curly braces line up in the source code, which makes it easier to detect when
one is missing, in addition to preventing typos like missing curly braces from occurring in the first
place, since you have a visual aid for their placement.
When function calls, like window.open in the example, are very long, sometimes the function call is bro-
ken up over multiple lines to make it easier to read. To the browser,
window.open(
this.href,
“picture”,
“scrollbars=no,width=300,height=280,resizable=yes”
);
and
window.open(this.href, “picture”, “scrollbars=no,width=300,height=280,resizable=yes”);
22
Part I: jQuery API
are exactly the same. The former example just makes it easier for humans to parse the arguments pres-
ent in the function call.
Sometimes these two conventions are mixed to form a third convention, which is known as the One
True Brace convention. This convention is defined in the Coding Standards Guidelines for PHP’s PEAR
repository.
window.onload = function()
{
var $nodes = document.getElementsByTagName(‘a’);
for (var $i = 0, $length = $nodes.length; $i < $length; $i++) {
$nodes[$i].onclick = function($e) {
window.open(
this.href,
“picture”,
“scrollbars=no,width=300,height=280,resizable=yes”
);
$e? $e.preventDefault() : (window.event.returnValue = false);
};
}
};
In the One True Brace convention, the function assigned to window.onload follows the Allman Style,
while the code within it follows K&R Style. This is the convention that I prefer for writing JavaScript,
since it’s more compact and leads to smaller file size, although I prefer the Allman Style for writing
non-JavaScript code for its greater readability, since with other languages, file size is less of an issue.
Which programming convention you use is a matter of personal taste. Often which convention to use
can lead to endless battles among programming teams, since sometimes people have different tastes.
You should use whichever convention makes the most sense for you. Although the three I’ve showcased
are the most popular, there are a multitude of variations that exist out in the wild. More information
about programming indention styles can be found on Wikipedia at http://en.wikipedia.org/wiki/
Indent_style.
Optional Curly Braces and Semicolons
In the conventions above, you’ll note that there is always a single space between the keyword that
begins the control structure, like if, and the opening parenthesis. The following is a switch control
structure using the first convention:
switch ($variable) {
case 1:
$condition = ‘this’;
break;
case 2:
$condition = ‘that’;
break;
default:
$condition = ‘those’;
}
23
Chapter 1: Introduction to jQuery
Note in the preceding that no break statement appears in the default case. As the default, a break is
implied, and it is necessary to include the break statement. I tend to deviate from the norm with how I
prefer switch control structures to be written.
switch ($variable) {
case 1:
{
$condition = ‘this’;
break;
};
case 2:
{
$condition = ‘that’;
break;
};
default:
{
$condition = ‘those’;
};
}
I like to add curly braces around each case in the switch statement; I do this because I believe it makes
the switch statement easier to read; however, ultimately, these are not necessary. Concerning optional
curly braces, I always include them, even if they’re technically optional. The same goes for semicolons.
Terminating each line with a semicolon is technically optional in JavaScript, although there are some
circumstances in which you won’t be able to omit it. I include all optional semicolons and curly braces,
as I think that this not only makes the code cleaner, more organized, and consistent, but also gives you
a technical benefit. If you want to compress your code to remove all additional white space, comments,
and so on, these optional bits suddenly are no longer optional, but needed to keep the program functional
once it’s been compressed. In the following example, you can see what I mean by optional components:
if ($condition)
$something = 1
else if ($another)
$something = 2
else
$something = 3
In JavaScript, the preceding code is perfectly valid. The semicolon is implied where there is a line break.
And as long as there is only a single statement being executed, technically you don’t have to include
curly braces. However, the above fails when it is compressed:
if ($condition) $something = 1 else if ($another) $something = 2 else $something = 3
The preceding fails with a syntax error when you try to execute it. It fails because the script interpreter
has no idea where you intend one statement to end and the next to begin. The language could probably
be extended to guess in some circumstances, but it’s better to just be as explicit as possible.
Something else that you might think is odd is the inclusion of a semicolon after some function defini-
tions. You’ll see this in JavaScript because a function can be a type of data, just like a number is a type
of data or a string is a type of data. In JavaScript, it’s possible to pass a function around as you would a
24
Part I: jQuery API
number or a string. You can assign a function to a variable and execute the function later. You’ve
already seen an example of this, and here it is again in the following code example:
window.onload = function()
{
var $nodes = document.getElementsByTagName(‘a’);
for (var $i = 0, $length = $nodes.length; $i < $length; $i++) {
$nodes[$i].onclick = function($e) {
window.open(
this.href,
“picture”,
“scrollbars=no,width=300,height=280,resizable=yes”
);
$e? $e.preventDefault() : (window.event.returnValue = false);
};
}
};
In the preceding code example, you can see that a function is being assigned to the onload event of the
window object. The function definition is terminated with a semicolon. Again, that semicolon is techni-
cally optional in this example, but I include it because I want the code to work if it gets compressed,
and I think that it makes the code more consistent, organized, and easier to follow.
Naming Variables, Functions, Objects, . . .
Variable naming is also accounted for in the coding standards I follow throughout this book. I always
use the camelCase convention when naming variables, functions, objects, or anything that I can poten-
tially invent a name for. I like to append a dollar sign ($) to local variable names (variables that are exe-
cuted within the scope of the currently executing function or object method). I name global variables
without a dollar sign to indicate that they are global. The dollar sign is technically optional in JavaScript.
You aren’t required to begin variable names with it, but I use it to assist with identifying variable scope.
Also, it’s worth noting that my use of the dollar sign originates from my roots as a PHP programmer,
where the dollar sign is a required prefix for variable names. Some people find this convention odd, so,
again, I implore you to do what makes the most sense to you.
Namespace JavaScript Code
It’s important to think about the big picture when writing an application. Whether you’re writing an
application for your own use or writing an application that will be deployed in varying environments
that you have no control over, you’re likely to run into one problem at some point in your career: nam-
ing conflicts. I touched on this topic when I talked about namespacing class and ID names in your CSS
and markup. The same principles I talked about there are also applicable to JavaScript. Your script appli-
cations need to run without invading the global namespace too much. I say “too much,” because you’ll
need to invade it somewhat, but you need to do so in a controlled and intelligent way. As you may have
done for your markup and CSS, namespacing your JavaScript may be as simple as sticking to object-
oriented code, wrapping all of your programs in just one, or a handful of objects and then naming those
objects in the global namespace in a non-invasive way. A common approach is to namespace those objects
with a prefix of some kind that doesn’t infringe on some other existing project. One example is how the
jQuery JavaScript framework is namespaced. jQuery does a lot, but for all of the code that’s included in
jQuery, there are precious few intrusions made on the global namespace, the “jQuery” object, and the
25
Chapter 1: Introduction to jQuery
dollar sign method the jQuery object is aliased to. All of the functionality that jQuery provides is pro-
vided through those objects.
Without a well-thought-out approach to the namespacing problem, it’s possible that your application may
cause conflicts with others. It’s best to just assume that everything you place in the global namespace will
cause a conflict, and thus set out to make as minimal as possible an intrusion into the global namespace.
Avoid Browser Detection
Browser detection can be a real annoyance. You’re surfing the Web using your favorite browser, and you
hit a website that locks you out — not because your web browser is technically incapable, but because it
didn’t match what the website’s creators presupposed would be capable. So, I propose the following:
Make no assumptions about the capabilities of a visitor’s browser.
❑
❑
Test for feature compatibility, rather than a browser name or browser version.
❑
❑
Account for the official standards and the de facto standards. (Official standards should take
❑
❑
precedence — de facto standards will either become or be replaced by the former.)
The world is always changing — what’s most popular today may not remain the most popular
❑
❑
in the months and years to come.
It may be time to turn to a framework for some compatibility bridging.
❑
❑
Anyone remember a little company called Netscape? At one time, Netscape was the dominant, de facto
standard. Now Netscape holds just under 0.6 percent of world market share, and Microsoft’s IE is domi-
nant. At its most popular, IE held more than 90 percent of the market. Now IE holds around 70 percent;
Firefox holds 21 percent; and Safari holds roughly 7 percent, Opera and others have around 2 percent
combined. The browsing market can and does fluctuate. In the real world, there are lots of people who
use less popular browsers. And 2 percent may sound small at first glance, but keep in mind that is 2
percent of a very large number. According to www.internetworldstats.com, in 2008, as I write this,
there are just over 1.4 billion Internet users world-wide, which is 21.9 percent of the world’s population.
Therefore, the so-called less popular browsers aren’t really doing too shabby in the grand scheme of
things, and while 2 percent sounds small, it’s actually a pretty large base of users.
Summary
jQuery takes what would otherwise be a more complex or verbose task in plain-vanilla JavaScript, and it
makes it much easier, sometimes reducing many lines to one or a few. Throughout this book, you will
learn about what jQuery has to offer and how to use its simple, easy-to-understand API to write spectacu-
lar, professional-appearing web applications that have all the polish and sparkle of a Fortune 500 company.
In this chapter, I talked a little about what jQuery is, where it comes from, and who develops and main-
tains it; and I showed you how to install it and begin using it. In the next chapter, you get right down to
business, learning about jQuery’s powerful implementation of the Selectors API and its world-class
Event API.
If you are interested in learning more about jQuery’s origins, visit www.jquery.com and www.ejohn.org.
26
Part I: jQuery API
This chapter also covered some things that a good programmer will want to get into the habit of doing,
such as adopting a formal programming convention and avoiding conflicts with others’ code through
using a namespace of some sort (whether that be via a feature provided by the language, or through
prefixing the names that you use that make an impact on the global namespace). I’ve shown a few of the
practices that I have adopted for myself, although I should emphasize that it doesn’t matter what pro-
gramming convention that you adopt, but rather that you adopt one. The premise of a programming
convention is that you have a set of rules that you can follow to format your code so that it is neat, orga-
nized, and easy to follow. My conventions might not be what you want, but there are many others to
choose from.
You should avoid detecting the user’s browser, especially when it may lead to one group or another
being locked out from functionality.
Your code should take advantage of client-side caching and the increase in performance it provides.
In my opinion, it is better to write code in neatly organized modules and combine those into a larger
script later using server-side programming.
Finally, it is also important that you adopt standards for the presentation and maintenance of client-side
markup and CSS. Choose either XHTML or HTML, since both are accepted standards. I personally use
XHTML, although XHTML may be too strict for your taste. Use the W3C’s validation services to discover
errors in your markup or your CSS, as sometimes errors in CSS or markup can cause errors in your
JavaScript.
2
Selecting and Filtering
In this chapter, I talk about jQuery’s sophisticated implementation of a Selectors API, which pro-
vides the ability to select elements in the DOM using selectors just like you use in CSS. jQuery’s
Selectors API allows you to select one or more elements from the DOM using a selector, then you
can either use that result set, or you can pass those elements on to be filtered down to a more spe-
cific result set.
If you’ve never heard of a selector before, then I recommend that you have a look at my book,
Beginning CSS: Cascading Style Sheets for Web Design, 2nd ed. (Wrox, 2004; ISBN 978-0-7645-7642-3),
which has extensive coverage of selectors.
In CSS, you can apply style to one or more elements by writing a style sheet. You choose which
elements to style based on the syntax that appears in the first part of a CSS rule, before the first
curly brace, which is known as the selector. Here is a sample CSS selector:
body form#hProductSummaryDialogue {
display: block;
position: absolute;
z-index: 1;
top: 22px;
left: 301px;
right: 0;
bottom: 24px;
width: auto;
margin: 0;
border: none;
border-bottom: 1px solid rgb(180, 180, 180);
}
Using markup and CSS, you are able to assign IDs and class names to elements, and you are able
to control the presentational aspects of elements very specifically using selectors. In jQuery, that
concept of selectors as applied to CSS is also applied to the concept of the DOM, or Document
Object Model. In the DOM, you have available to you every element that exists in the markup of
your document, and you are able to travel the DOM and select the elements you want to work
with using selectors, just like you use in your CSS style sheets.
28
Part I: jQuery API
Once you’ve selected elements from the DOM, you can apply behavior to them. You can make some-
thing happen when a user clicks on an element, for example. You can make something happen when
the user’s mouse cursor comes over or leaves an element. Basically, you can make your web documents
look and behave more like desktop applications. You are no longer limited to static content as you are
with markup and CSS alone — you can apply behavior as well.
In this chapter, I describe how to use jQuery’s Selectors API to retrieve elements from a document, in
addition to providing some practical examples of usage. I also describe how you can chain calls in jQuery.
One use for this is filtering elements, which you would do to reduce a larger selection of elements down
to a smaller selection. Finally, I discuss how jQuery’s Event API works in relation to the W3C’s Event
API and Microsoft’s.
The Origin of the Selectors API
The concept of a Selectors API was first dreamed up by Dean Edwards, a JavaScript guru, who first cre-
ated a Selectors API in JavaScript in a free, Open Source package he called cssQuery. Not long after Dean
pioneered the idea and produced a working, proof-of-concept implementation of that idea, it was taken
up and expanded upon by John Resig (and other JavaScript framework authors, mutually exclusive to
John’s efforts) and implemented in his jQuery framework. This led to some back-and-forth collaboration
and competition between Dean, John, and other JavaScript framework authors, which resulted in much
needed performance boosts in these ad hoc implementations, which at their conception were quite slow
in some scenarios.
Not long after Dean came up with the concept of a Selectors API, W3C members and editors Anne van
Kesteren and Lachlan Hunt drafted it into a specification for the W3C. The official W3C Selectors API
involves two methods, one for selecting a single element called document.querySelector() and one for
selecting multiple elements called document.querySelectorAll().
The names for the official API were under considerable debate for quite some time, as no browser
makers could agree on the names used. The names were finally put to a vote, with these names being
the ones decided on. The controversy surrounding the names was not without merit, as this API is
quite possibly the most important change to JavaScript that will have a lasting impact for years to
come. It’s important in that, in one fell swoop, it replaces methods like document.getElementById,
document.all, and document.getElementsByTagName, which are no longer really needed — since
these methods let you use selector syntax, you can select by ID, by tag name, by class name, or by
context, via whatever selectors the browser already supports for CSS.
As I write this, the W3C version is a Candidate Recommendation, and document.querySelector and
document.querySelectorAll are implemented natively in Internet Explorer 8, Safari 3, Firefox 3.1, and
Opera 10. For once, a new feature is present and accounted for in the latest releases of all of the major
browsers!
The great thing about jQuery and other JavaScript frameworks is that they had their own versions of
the Selectors API already implemented prior to its native inclusion in browsers, which allows them to
use the native implementation, if it is available. Using the native implementation makes selecting ele-
ments screamingly fast. Otherwise, if the user has an older browser, the framework can fall back on its
own, slower, JavaScript-based implementation. This means that when using a JavaScript framework like
jQuery, the Selectors API is ubiquitously available across all platforms it supports. jQuery is officially
compatible with IE 6+, Firefox 1.5+, Safari 2.0.2+, and Opera 9+.
29
Chapter 2: Selecting and Filtering
Using the Selectors API
Using the Selectors API in jQuery is very easy. First, you must know that everything you want to do
with jQuery originates from a single, very simply named object that is called $. That’s right, its name is a
single dollar sign. As I mentioned back in Chapter 1, you can also use “jQuery” in place of the dollar sign,
but from here on throughout this book, I will use only the dollar sign, and I will refer to it either as “the
dollar sign object” or “the dollar sign method,” depending on context, because it is really both a method
and an object at the same time.
The dollar sign is both a method and an object because it can be used like a function call, but it also has
member properties and methods that you can call. The dollar sign is named after a single dollar sign for
one reason only, and that is to reduce the amount of code that you have to write. This is why a dollar
sign is used instead of, say, document.getElementsBySelector(), which is very long, verbose, and
annoying to type out.
Here’s a very simple example of how you would use this method with a selector to add a click behavior
to a collection of links. Basically, the object of the following code is to force the links to open in a new
window, instead of using the “target” attribute, which does not validate under XHTML Strict.
Let’s say that you have a markup document that looks like this:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=’http://www.w3.org/1999/xhtml’ xml:lang=’en’>
<head>
<meta http-equiv=’content-type’ content=’text/html; charset=utf-8’ />
<meta http-equiv=’content-language’ content=’en-us’ />
<title>Link</title>
<script type=’text/javascript’
src=’../../../Source Code/jQuery/jQuery.js’>
</script>
<script type=’text/javascript’ src=’Figure 2-1.js’></script>
<link type=’text/css’ href=’Figure 2-1.css’ rel=’stylesheet’ />
</head>
<body>
<ul id=’tmpFavorites’>
<li><a href=’http://www.wrox.com’>Wrox</a></li>
<li><a href=’http://www.gizmodo.com’>Gizmodo</a></li>
<li><a href=’http://www.apple.com’>Apple</a></li>
<li><a href=’http://www.jquery.com’>jQuery</a></li>
</ul>
</body>
</html>
In the preceding markup document, you have a simple unordered list that contains four links. You take
that markup and put it with the following CSS:
body {
font: 16px sans-serif;
}
ul {
list-stlye: none;
30
Part I: jQuery API
margin: 0;
padding: 0;
}
a {
text-decoration: none;
}
The preceding CSS document does little more than make that list look a little prettier — it neither really
adds to nor takes away from the example.
Finally, you add the following JavaScript document to the markup:
var tmpExample = {
ready : function() {
// Get all links…
$(‘ul#tmpFavorites li a’).click(
function($e) {
$e.preventDefault();
window.open(this.href, ‘FavoriteLink’, ‘’);
}
);
}
};
$(document).ready(tmpExample.ready);
The preceding code, all put together, should look something like what you see in Figure 2-1.
Figure 2-1
When you click on a link in the example, you should see the link open in a new window or tab, depend-
ing on how you have your browser’s preferences set up to handle pop-up windows.
In the preceding example, you’re using JavaScript to force the links in the <ul> element with ID name
tmpFavorites to open in a new window or tab. To do this, in the JavaScript, you created a JavaScript
Object Literal, which isn’t the only way to create a new object — there are lots of ways to do this, but I just
happen to like this one. The new object is called tmpExample, and it has one member method, called
ready; then inside the ready method are all the things you want to do when the document is ready.
Another Random Scribd Document
with Unrelated Content
TESSELLATED PAVEMENT
From Lysons’ Account of the Roman Villa discovered at Woodchester.
The character of the Roman remains dug up from time to time
within these walls shows that it was formerly a place of great resort.
Under the protection of this citadel, and later under the protection of
the Pax Romana, villas were built up outside the walls for the
residence of the better sort. All round the walls also sepulchral
remains have been discovered; they were afterwards included in the
larger wall of the city which was built towards the close of the fourth
century.
London was then, and for many years afterwards, divided into
London east and west of the Walbrook. On the western side was the
quarter of the poorer sort; they had cottages on the foreshore—as
yet there was no wall. The better class lived outside the fort, along
the eastern side of Walbrook, and in Cornhill, Threadneedle Street,
and Bishopsgate Street. Down below were the three Roman ports,
afterwards called Billingsgate, Dowgate, and Queenhithe. Walking
down Thames Street one finds here and there an old dock which
looks as if it had been there from time immemorial.
I have sometimes been tempted, when in Thames Street—that
treasure-house of memories, survivals, and suggestions—to think
that these narrow lanes sloping to the river are of Roman origin, left
when all the rest was wrecked and lost, and that they are still of the
same breadth as they were in the fourth century. This, however, is
not the case. I shall show presently the origin and meaning of these
narrow streets running up the hill from the river into Thames Street:
they are all, in fact, connections of the quays on the foreshore with
the merchants’ warehouses in Thames Street. Along the better
streets, on the north of Thames Street, the traders put up their stalls
and kept their shops; the stalls were at first mere temporary sheds
resting against the walls of villas. These villas belonged, not to the
millionaire Lucullus, for whose palace the whole world could be
ransacked, but to the well-to-do merchant, whose taste was not
much cultivated. He called in the best artist of the city. “Build me a
villa,” he said, “as good as my neighbour’s. Let there be a fine
mosaic pavement; let there be fountains; let there be paintings on
the walls, lovely paintings—nymphs and fauns, nymphs bathing,
plenty of nymphs, dancing girls, plenty of dancing girls; paint me
Hercules drunk, Loves flying and playing tricks, warriors with shields,
sea pieces, ships; paint me my own ships sailing. And take care of
the hypocaust and the warming pipes, and see that the kitchen is
suitably furnished.”
The earliest, the natural port of London was the mouth of the
Walbrook, called afterwards Dowgate.
In the western wall of the Roman citadel was the gate which
served at once for the road or street across the City to Newgate, and
for that part of the trade which belonged to the citadel. The
Walbrook at this time was a considerable stream. It was partly a
tidal stream, but it was fed from above by many tributaries on the
moorland. Here the ships first began to load and to unload. For their
convenience quays were constructed on piles driven into the mud
and shingle of the foreshore. As the trade increased, the piles were
pushed out farther and the quays were broadened.
When trade increased and the difficulties of getting through the
bridge were felt, another port was necessary. It was perfectly easy
to construct one by cutting it out of the soft foreshore and then
banking it up with strong piles of timber. Piles and beams were also
driven in on either side for the support of quays, which could thus be
extended indefinitely. The place chosen was what is now called
Billingsgate. It was close to the bridge and the bridge gate; so that
while goods could be landed here for the trade of the City—whence
they could be easily distributed throughout the north and midland of
the island,—communication was established with the south by
means of the bridge (see Appendices I. and II.).
Later on, but one knows not when, the port of Queen Hythe,
formerly Edred’s Hythe, was similarly constructed. I am inclined to
believe also that Puddle Dock represents another ancient port; but
whether Roman or Saxon, it is now impossible to decide.
The poorer part of the City was that part lying between Puddle
Dock and Dowgate: we do not find tessellated pavements here, nor
remains of great buildings. The houses which stood upon the
pavements were modest compared with the villas of the Roman
millionaire; but they were splendid compared with other houses of
the City.
For the convenience of the better sort there was the bath, in
which everybody spent a part of the day; for the merchants there
were the quays; there was the theatre; and there was the
amphitheatre. It is true that no trace has ever been found of theatre
or of amphitheatre; but it is also true that until recently no trace was
found of the Roman citadel, and, as I have said, no trace has ever
been found of forum or of temples. We will return to this subject
later.
To one standing at the south end of the narrow wooden bridge
across the Thames, Augusta, even before the building of the wall,
appears a busy and important place. Exactly opposite the bridge, on
a low eminence, was a wall, strong though low, and provided with
rounded bastions. Above the wall were seen the columns of the
forum and of two temples, the roofs of the great hall of justice and
of the official offices and residences.
Along the quays were moored the ships. On the quay stood sheds
for warehouses in a line. Behind these warehouses were barracoons
for the reception of the slaves waiting to be transported to some
other part of the Empire, there to await what Fortune had in store
for them—perhaps death in a gladiatorial fight, perhaps service on a
farm, perhaps the greatest gifts of Fortune, viz. a place in a Roman
cohort, opportunities for showing valour and ability, an officer’s
commission, the command of a company, then of a legion, then of a
victorious army; finally, perhaps the Purple itself and absolute rule
over all the civilised world. The streets behind the warehouses were
narrow and steep, the houses in them were mean. Everywhere
within the area afterwards enclosed by the wall were villas, some
small, some large and stately. It was a noisy city, always a noisy city
—nothing can be done with ships without making a noise. The
sailors and the stevedores and the porters sang in chorus as they
worked; the carts rolled slowly and noisily along the few streets
broad enough to let them pass; mules in single file carried bales in
and out of the city; slaves marched in bound and fettered; in the
smaller houses or in workshops every kind of trade was carried on
noisily. Smoke, but not coal smoke, hung over all like a canopy.
In such a restoration of a Roman provincial town one seems to
restore so much, yet to leave so much more. Religion, education,
literature, the standard of necessities and of luxury, the daily food,
the ideas of the better classes, the extent, methods, and nature of
their trade, the language, the foreign element—none of these things
can be really restored.
Under the protection of the citadel the merchants conducted their
business; under its protection the ships lay moored in the river; the
bales lay on the quays; and the houses of the people, planted at first
along the banks of the Walbrook, stretched out northwards towards
the moor, and westwards as far as the river Fleet.
It is strange that nothing should be said anywhere about so strong
and important a place as the citadel. When was it built, and by
whom? When was it destroyed, and by whom? Were the walls
standing when the Saxons began their occupation? It appears not,
because, had there been anything left, any remains or buildings
standing, any tradition of a fortress even, it would have been carried
on. The citadel disappeared and was forgotten until its foundations
were found in our time. How did this happen? Its disappearance can
be explained, according to my theory, by the history of the wall (see
p. 112): all the stones above ground, whether of citadel, temple,
church, or cemetery, were seized upon to build the wall.
Across the river stood the suburb we now call Southwark, a
double line of villas beside a causeway. It has been suggested that
Southwark was older than London, and that it was once walled in.
The only reasons for this theory are: that Ptolemy places London in
Kent—in which he was clearly wrong; that the name of Walworth
might indicate a city wall; that remains of villas have been found in
Southwark; and that a Roman cemetery has been found in the Old
Kent Road. But the remains of houses have only been found beside
the high road leading from the bridge. They were built on piles
driven into the marsh. Up till quite recent times the whole south of
London remained a marsh with buildings here and there; they were
erected on a bank or river wall, on the Isle of Bermond, on the Isle
of Peter, beside the high road. And there has never been found any
trace of a wall round Southwark, which was in Roman times, and has
always been, the inferior suburb—outside the place of business and
the centre of society. Every town on a river has an inferior suburb on
the other side—London, Paris, Liverpool, Tours, Florence: all busy
towns have inferior transpontine suburbs. Southwark was always a
marsh. When the river-bank was constructed the marsh became a
spongy field covered with ponds and ditches; when the causeway
and bridge were built, people came over and put up villas for
residence. In the Middle Ages there were many great houses here,
and the place was by some esteemed for its quiet compared with
the noise of London, but Southwark was never London.
Besides the bridge, there was a ferry—perhaps two ferries. The
name of St. Mary Overies preserves the tradition. There are two very
ancient docks, one beside the site of the House of St. Mary Overies,
and one opposite, near Walbrook. In these two docks I am pleased
to imagine that we see the ancient docks of London ferry to which
belongs the legend of the foundation of the House.
Let us return to the question of amphitheatre and theatre. There
must have been both. It is quite certain that wherever a Roman
town grew up an amphitheatre grew up with it. The amphitheatre
was as necessary to a Roman town as the daily paper is to an
American town.
It has been suggested that there was no amphitheatre, because
the city was Christian. There may have been Christians in the city
from the second century; everything points to the fact that there
were. It is impossible, however, to find the slightest trace of
Christian influence on the history of the city down to the fourth
century. W. J. Loftie thinks that the dedication of the churches in the
lower and poorer parts of the town—viz. to SS. Peter, Michael,
James, and All Saints—shows that there were Christian churches on
those sites at a very early period. This may be true, but it is pure
conjecture. It is absurd to suppose that a city, certainly of much
greater importance than Nîmes or Arles—where were both theatre
and amphitheatre,—and of far greater importance than Richborough
—where there was one,—should have no trace of either. Since
Bordeaux, Marseilles, Alexandria, and other cities of the Roman
Empire were not Christian in the second and third centuries, why
should London be? Or if there were Christians here in quite early
times, theirs was not the dominant religion, as is clearly shown by
the Roman remains. There must have been an amphitheatre—where
was it? To begin with, it was outside the City. Gladiators and slaves
reserved for mock battles which were to them as real as death could
make them, wild beasts, the company of ribalds who gathered about
and around the amphitheatre, would not be permitted within the
City. Where, then, was the amphitheatre of London?
At first one turns to the north, with its gardens and villas and
sparse population. The existence of the villas will not allow us to
place the amphitheatre anywhere in the north near the Walbrook.
When the modern traveller in London stands in the churchyard of
St. Giles’s, Cripplegate, he looks upon a bastion of the Roman wall
where the wall itself took a sudden bend to the south. It ran south
till it came to a point in a line with the south side of St. Botolph’s
Churchyard (the “Postmen’s Park”), where it again turned west as far
as Newgate.
It thus formed nearly a right angle—Why? There is nothing in the
lie of the ground to account for this deviation. No such angle is
found in the eastern part of the wall. There must have been some
good reason for this regular feature in the wall. Was the ground
marshy? Not more so than the moorland through which the rest of
the wall was driven. Can any reason be assigned or conjectured? I
venture to suggest, as a thing which seems to account for the
change in the direction of the wall, that this angle contained the
amphitheatre, the theatre, and all the buildings and places, such as
the barracks, the prisons, the dens and cages, and the storehouse,
required for the gladiatorial shows. I think that those who built the
wall, as I shall presently show, were Christians; that they were also,
as we know from Gildas, superstitious; that they regarded the
amphitheatre, and all that belonged to it, as accursed; and that they
would not allow the ill-omened place of blood and slaughter and
execution to be admitted within the walls. It may be that a tradition
of infamy clung to the place after the Roman occupation: this
tradition justifies and explains the allocation to the Jews of the site
as their cemetery. The disappearance of the amphitheatre can be
fully explained by the seizure of the stones in order to build the wall.
Mr. C. Roach Smith, however, has proposed another site for the
theatre, for which he tenders reasons which appear to me not,
certainly, to prove his theory, but to make it very possible and even
probable. Many Roman theatres in France and elsewhere are built
into a hill, as the rising ground afforded a foundation for the seats.
That of Treves, for instance, will occur to every one who has visited
that place. Mr. Roach Smith observed a precipitous descent from
Green Arbour Court into Seacoal Lane—a descent difficult to account
for, save by the theory that it was constructed artificially. This indeed
must have been the case, because there was nothing in the shape of
a cliff along the banks of the Fleet River. Then why was the bank cut
away? Observe that the site of the Fleet Prison was not on a slope at
all, but on a large level space. We have therefore to account for a
large level space backed by an artificial cliff. Is it not extremely
probable that this points out the site of the Roman theatre, the seats
of which were placed upon the artificial slope which still remains in
Green Arbour Court?
Mr. Roach Smith read a paper (Jan. 1886) placing this discovery—
it is nothing less—on record before the London and Middlesex
Archæological Association. The remarkable thing is that no one
seems to have taken the least notice of it.
Assuming that he has proved his case, I do not believe that he is
right as to the houses being built upon the foundations of the
theatre, for the simple reason that, as I read the history of the wall
in the stones, every available stone in London and around it was
wanted for the building of the wall. It was built in haste: it was built
with stones from the cemeteries, from the temples, from the
churches, from the old fortress, and from the theatre and the
amphitheatre outside the wall. As regards the latter, my own view
remains unaltered; I still think that the angle in the wall was caused
by the desire to keep outside the amphitheatre with all its memories
of rascality and brutality.
Treves (Colonia Augusta Treverorum) and Roman London have
many points in common, as may be apprehended most readily from
the accompanying comparison in which Roman Treves and Roman
London are placed side by side. We may compare the first citadel of
London on the right bank of the Walbrook with Treves; or we may
compare the later London of the latter part of the fourth century, the
wall of which was built about a.d. 360-390, with Treves.
1. The citadel of London had its western side protected by a valley
and a stream whose mouth formed a natural port. The valley was
about 140 feet across; the stream was tidal up to the rising ground,
with banks of mud as far, at least, as the north wall of the citadel.
On the south was a broad river spanned by a bridge. There were
three gates: that of the north, that of the west, and that of the
bridge on the south. Within the citadel were the official buildings,
barracks, residences, and offices. Two main streets crossed at right
angles. About half a mile to the north-west (according to my theory)
was the amphitheatre. On the north and east was an open moor. On
the south a marsh, with rising ground beyond. By the river-side,
near the bridge, were the baths.
2. Colonia Augusta Treverorum.—These details are almost exactly
reproduced in Treves. We have a broad river in front. On one side a
stream which perhaps branched off into two. The gate which
remains (the Porta Nigra) shows the direction of the wall on the
north from the river. A long boulevard, called at present the Ost
Allee, marks the line of the eastern wall, which, like that of London,
occupied the site of the Roman wall. A bend at right angles at the
end of this boulevard includes the Palace and other buildings. It
therefore represents the site of the ancient wall or that of a
mediæval wall. It is quite possible that the mediæval wall of the city
included a smaller area than the Roman wall, and that the two round
towers, here standing in position with part of the wall, represent the
mediæval wall. It is also possible, and even probable, that they
stand on the site of the Roman wall, which just below the second, or
at the second, bent round again to the south as far as the stream
called the Altbach, and so to the west as far as the river. That this,
and not the continuation of the line of towers, was the course of the
Roman wall, is shown by the fact that the baths, the remains of
which stand beside the bridge, must have been within, and not
outside, the wall. The river wall, just like that of London, ran along
the bank to the bridge, and was stopped by the outfall of a small
stream. The ground behind the river wall gradually rose. On the
other side was a low-lying marsh, beyond which were lofty hills—not
gradually rising hills as on the Surrey side of the Thames. The city
was crossed by two main arteries, which may still be traced. An
extensive system of baths was placed near the bridge on the east
side. Within the wall were the Palace of the Governor or of the
Emperor, and a great building now called the Basilica; and between
them, the remains now entirely cleared away for the exercise
ground, once the garden of the barracks. There were three gates,
perhaps four. One of them, a most noble monument, still survives. A
Roman cemetery has been found beyond the Altbach in the south,
and another in the north, outside the Porta Nigra.
3. The comparison of Roman Treves with the later Roman London
is most curious, and brings out very unexpectedly the fact that in
many respects the latter was an enlargement of the citadel. We
know that the wall was constructed hastily, and that all the
stonework in the City was used in making it. Like the citadel,
however, and like Treves, it had a stream on one side, baths and a
bridge and a port within the walls; while the official buildings, as at
Treves, were all collected together in one spot. We also find the
curious angle, which at Treves may be accounted for by an
enlargement of the wall, and at London by the custom of keeping
the amphitheatre outside the City as a place foul with associations of
battle, murder, massacre, and the ribald company of gladiators,
retiarii, prisoners waiting the time of combat and of death, wild
beasts and their keepers, and the rabble rout which belonged to this
savage and reckless company.
That part of London lying to the west of Walbrook was crowded
with the houses of the lower classes, and with the warehouses and
stores of the merchants. These extended, as they do to this day, all
the way from the Tower to Blackfriars. On the rising ground above
were the villas of the better class, some of them luxurious, ample,
decorated with the highest art, and provided with large gardens.
These villas extended northwards along the banks of the little
Walbrook. They are also found on the south side in Southwark, and
on the west side on Holborn Hill. The principal street of Augusta was
that afterwards called Watling Street, which, diverted from the old
Watling Street where Marble Arch now stands, carried all the trade
of the country through London by way of Newgate, over the present
site of St. Paul’s, and so through the citadel, to the market-place and
to the port. Another street led out by way of Bishopsgate to the
north; and a third, the Vicinal Way, to the eastern counties. The
bridge led to a road running south to Dover. There was also a long
street, with probably many side streets out of it, as there are at this
day, along the Thames.
The things which remain of Roman London and may be seen in
our museums are meagre, but they yield a good deal of information
as to the condition and the civilisation of the City. The foundation of
large villas, the rich mosaics and pavements, the remains of statues,
the capitals of pillars, the coins, and the foundations of massive
walls, clearly indicate the existence of much wealth and considerable
comfort. The smaller things in the glass cases, the keys, the
hairpins, the glass bottles, the statuettes, the bells, the tools, the
steelyards, the mirrors, all point to a civilisation closely imitating that
of the capital itself.
It is not to a native of London that we must turn for the life of the
better class in a provincial city of the fourth century, but to a native
of Gaul. Ausonius is a writer whose works reveal the daily life of a
great city in Gaul. He was born of good family on both sides. His
father was a physician; his grandfather a so-called “Mathematician,”
in reality one who still practised the forbidden mystery of astrology.
Ausonius himself was educated at Toulouse, and he opened a school
of rhetoric at Bordeaux. The rhetoricians not only taught, but also
practised, the art of oratory. Whether all rhetoricians were also poets
is uncertain: the mere making of verse is no more difficult to acquire
than the composition of oratory. There were two classes of teachers:
the grammarian, of whom there were subdivisions—the Latin
ROMAN SANDALS TAKEN FROM THE BED OF
THE THAMES
Roach Smith’s Catalogue of London Antiquities.
grammarian, skilled in
Latin antiquities, and the
Greek grammarian, who
had studied Greek
antiquities; and, above
the grammarian, the
rhetorician. In every
important town over the
whole Empire were found
the rhetorician and the
grammarian; they
exchanged letters, verses,
compliments, and
presents. In a time of
universal decay, when no
one had anything new to
say, when there was
nothing to stimulate or
inspire nobler things, the
language of compliment,
the language of
exaggeration, and the language of conceit filled all compositions. At
such a time the orator is held in greater respect even than the
soldier. In the latter the townsman saw the preserver of order, the
guardian of the frontier, the slayer of the barbarians who were
always pressing into the Empire. He himself carried no arms: he
represented learning, law, literature, and medicine. Ausonius himself,
in being elevated to the rank of consul, betrays this feeling. He
compares himself with the consuls of old: he is superior, it is evident,
to them all, save in one respect, the warlike qualities. These virtues
existed no longer: the citizen was a man of peace; the soldier was a
policeman. If this was true of Bordeaux, then far from the seat of
any war, it was much more true in London, which every day saw the
arrival and the dispatch of slaves captured in some new border fray,
while the people themselves never heard the clash of weapons or
faced the invader with a sword.
Another profession held greatly in honour was that of the lawyer.
The young lawyer had a five years’ course of study. There were
schools of law in various parts of the Empire which attracted
students from all quarters, just as in later times the universities
attracted young men from every country. From these lawyers were
chosen the magistrates.
Medicine was also held greatly in honour; it was carefully taught,
especially in southern Gaul.
THE LACONICUM, OR SWEATING BATH
From Lysons’ Account of the Roman Villa at Woodchester.
The learned class was a separate caste: with merchants and
soldiers, the lawyers, orators, grammarians, and physicians had
nothing to do. They kept up among themselves a great deal of the
old pagan forms. If they could no longer worship Venus, they could
write verses in the old pagan style about her. Probably a great many
continued, if only from habit, the pagan customs and the pagan
manner of thought. The Church had not yet given to the world a
crowd of saints to take the place of the gods, goddesses, nymphs,
satyrs, and sprites which watched over everything, from the Roman
Empire itself down to a plain citizen’s garden.
The theatre was entirely given over to mimes and pantomimes:
comedy and tragedy were dead. The pieces performed in dumb
show were scenes from classical mythology. They were presented
with a great deal of dancing. Everybody danced. Daphne danced
while she fled; and Niobe, dancing, dissolved into tears. The circus
had its races; the amphitheatre its mimic contests and its gladiatorial
displays.
These things were done at Bordeaux; it is therefore pretty certain
that they were also done in London, whose civilisation was equally
Gallo-Roman. London was a place of importance equal with
Bordeaux; a place with a greater trade; the seat of a Vicarius
Spectabilis, a Right Honourable Lieutenant-Governor; one of the
thirteen capitals of the thirteen Dioceses of the Roman Empire.
TESSELLATED PAVEMENT
From Lysons’ Account of the Roman Villa at Woodchester.
Any account of Roman London must include a description and plan
of a Roman villa. The one I have chosen is the palatial villa which
was recovered by Samuel Lysons exactly a hundred years ago at
Woodchester. The plan is given in his book, An Account of Roman
Antiquities discovered at Woodchester; it shows the arrangement of
the rooms and the courts.
“The visitor approaching this villa when it was standing observed
before him a long low wall with an entrance arch. The wall was
probably intended as some kind of fortification; the people in the
house numbered enough to defend it against any wandering
company of marauders. Within the entrance, where he was received
by a porter or guard, the visitor found himself in a large square
court, the sides of which were 150 feet. On either side, to east and
west, were buildings entered from the great court: in one there were
twelve rooms; in the other a curious arrangement of rooms
communicating with each other which were thought to be the baths.
The rooms on the west side were perhaps the chambers and
workshops of the slaves and servants.
On the north side a smaller gateway gave access to a court not so
large as the first, but still a good-sized court, 90 feet square; it was
surrounded on three sides by a gallery, which was closed in winter,
as the hypocaust under it indicates. From this court access was
obtained to a lovely hall, decorated with a mosaic pavement of great
artistic value, with sculptures, paintings, vases, and glass. On either
side of this hall were chambers, also decorated in the same way.
Under the floors of the chambers was the hypocaust, where were
kindled the fires whose hot air passed through pipes warming all the
chambers. Fragments of statues, of which one was of Magnentius
the usurper, also glass, pottery, marble, horns, coins. The building
covered an area of 550 feet by 300 feet, and it is by no means
certain that the whole of it has been uncovered.
It is interesting to note that on one of the mosaics found at this
place is the injunction ‘... B][N][C ...’18—that is, Bonum Eventum
Bene Colite—Do not forget to worship Good Luck. To this god, who
should surely be worshipped by all the world, there was a temple in
Rome.
The Roman Briton, if he lived in such state as this, was fortunate
above his fellows. But in the smaller villas the same plan of an open
court, square, and built upon one, two, or more sides, prevailed. The
walls were made of stone up to a certain height, when wood took
the place of stone; the uprights were placed near together, and the
interstices made air-tight and water-tight with clay and straw; the
roof was of shingles or stone tiles. Wall paintings have been found
everywhere, as we have already seen; the pavements were in many
cases most elaborate mosaics.”
The construction of a villa for a wealthy Roman Briton is easy to
be understood. As to the question of the smaller houses, it is not so
easy to answer. A small house, detached, has been found at
Lympne. It was about 50 feet long and 30 feet broad. The plan
shows that it was divided into four chambers, one of which had a
circular apse. The rooms were all about the same size, namely,
above 22 feet by 14 feet. A row of still smaller houses has been
found at Aldborough. Almost all the streets in London stand upon
masses of buried Roman houses. If we wish to reconstruct the city,
we must consider not only the villas in the more open spaces as the
official residences in the citadel, but also the streets and alleys of the
poorer sort. Now at Pompeii the streets are narrow; they are
arranged irregularly; there are only one or two in which any kind of
carriage could pass. The same thing has been observed at Cilirnum
(Chesters), in Northumberland, and at Maryport in Cumberland. Very
likely the narrow streets leading north of Thames Street are on the
same sites as the ancient Roman streets of London in its poorer and
more crowded parts. It stands to reason that the houses of the
working people and the slaves could not be built of stone.
The nature of the trade of London is arrived at by considering—(1)
What people wanted; (2) what they made, produced, and grew for
their own use; and (3) what they exported.
ROMAN ROADS RADIATING FROM LONDON
To take the third point first. Britain was a country already rich. The
south part of the island, which is all that has to be considered,
produced iron, tin, lead, and copper; coal was dug up and used for
fuel when it was near the surface; skins were exported; and the
continual fighting on the march produced a never-failing supply of
slaves for the gladiatorial contests. Wheat and grain of all kinds were
also largely grown and exported.
As for manufactures, pottery was made in great quantities, but not
of the finer kinds. Glass was made. The art of weaving was
understood. The arts of painting, mosaic work, and building had
arrived at some excellence. There were workmen in gold and other
metals.
As for what people wanted. Those who were poor among them
wanted nothing but what the country gave them; for instance, the
river was teeming with fish of all kinds, and the vast marshes
stretching out to the mouth of the Thames were the homes of
innumerable birds. No one need starve who could fish in the river or
trap birds in the marsh. In this respect they were like the common
sort, who lived entirely on the produce of their own lands and their
own handiwork till tea, tobacco, and sugar became articles of daily
use. The better class, however, demanded more than this. They
wanted wine, to begin with; this was their chief want. They wanted,
besides, silks for hangings and for dress, fine stuffs, statues, lamps,
mirrors, furniture, costly arms, books, parchment, musical
instruments, spices, oil, perfumes, gems, fine pottery.
The merchants of London received all these things, sent back the
ships laden with the produce of the country, and dispatched these
imported goods along the high roads to the cities of the interior and
to the lords of the villas.
London was the centre of at least five great high roads. In this
respect it was alone among the towns of Roman Britannia. These
highways are laid down in Guest’sOrigines Celticæ. They connect the
City with every part of the island: on the north-east with Colchester;
on the north with Lincoln and York; on the north-west with
Uriconium (Wroxeter), for Shrewsbury and Wales and Ireland; on the
west with Silchester, for Winchester and Salisbury; on the south-east
with Richborough, Dover, and Lympne or Lymne; and on the south
with Regnum (Chichester)—if we may fill in the part between
London and Dorking which Guest has not indicated.
This fact is by itself a conclusive proof that London was the great
commercial centre of the island, even if no other proofs existed. And
since the whole of the trade was in the hands of the London
merchants, we can understand that in times when there was a
reasonable amount of security on the road and on the Channel,
when the Count of the Saxon Shore patrolled the high seas with his
fleet, and the Duke of Britain kept back the Scot and the Pict, the
city of Augusta became very wealthy indeed. There were, we have
seen, times when there was no safety, times when the pirate did
what he pleased and the marauder from the north roamed
unmolested about the country. Then the London merchants suffered
and trade declined. Thus, when Queen Boadicea’s men massacred
the people of London, when the soldiers revolted in the reign of
Commodus, when the pirates began their incursions before the
establishment of the British fleet, when Carausius used the fleet for
his own purposes, and in the troubles which preceded and followed
the departure of the legion, there were anxious times for those
engaged in trade. But, on the whole, the prosperity of London was
continuous for three hundred and fifty years.
CHAPTER IV
REMAINS OF ROMAN LONDON
If one stands in the Museum of the Guildhall and looks round
upon the scanty remains of Roman London there exhibited, one feels
a cold doubt as to the alleged wealth and greatness of the ancient
city. Is this all that has to be shown after an occupation of nearly
four hundred years? There is not much more: one may find a room
at the British Museum devoted to this subject; and there are a few
small private collections containing nothing of importance. Yet when
we consider the length of time since Roman London fell; the long
history of reconstruction, fire, and successive occupations; the fact
that twice—once for more than a hundred years—London was
entirely deserted, we must acknowledge that more remains of
Roman London than might have been expected. What exists, for
instance, of that other great Roman city now called Bordeaux? What,
even, of Lutetia Parisiorum? What of Massilia, the most ancient of
Gallic cities?
There are, however, many remains of Roman London which are
not preserved in any collection. Some are above ground; some have
been dug up and carried away; some have been disclosed,
examined, sketched, and again covered up.
Antiquaries have been pleased to find traces of Roman relics of
which no memory or tradition remains. Thus, we are assured that
there was formerly a Campus Martius in London; its site is said to
have been that of the Old Artillery Ground. A temple of Diana is said
to have stood on the south side of St. Paul’s. There was a
mysterious and extensive crypt called the Camera Dianæ, supposed
to have been connected with the worship of that goddess; it was
standing in the seventeenth century. Probably it was the crypt of
some mediæval house. Stukeley persuaded himself that he found in
Long Acre the “magnificent circus, or racecourse, founded by Eli,
father of Casvelhun”; he also believed that he had found in Hedge
ROMAN ALTAR TO DIANA FOUND
IN ST. MARTIN’S-LE-GRAND
Lane the survival of the agger or
tumulus of King Eli’s grave. The same
antiquary preferred to trace Julius
Cæsar’s Camp in the Brill opposite old
St. Pancras Church.
It is sometimes stated that
excavations in London have been few
and scattered over the whole area of
the City; that there has been no
systematic and scientific work carried
on such as, for instance, was
conducted, thirty years ago, at
Jerusalem by Sir Charles Warren. But
when we consider that there is no
single house in the City which has not
had half a dozen predecessors on the
same site, whose foundations,
therefore, have not been dug up over
and over again, no one can form any
estimate of the remains, Roman, British, and Saxon, which have
been dug up, broken up, and carted away. During certain works at
St. Mary Woolnoth, for instance, the men came upon vast remains of
“rubbish,” consisting of broken pottery and other things, the whole
of which were carried off to St. George’s Fields to mend or make the
roads there. The only protection of the Roman remains, so long as
there was no watch kept over the workmen, lay in the fact that the
Roman level was in many places too deep for the ordinary
foundations. Thus in Cheapside it was 18 feet below the present
surface; in other places it was even more.
The collection of Roman antiquities seems to have been first
undertaken by John Conyers, an apothecary, at the time of the Great
Fire. The rebuilding of the City caused much digging for foundations,
in the course of which a great many Roman things were brought to
light. Most of these were unheeded. Conyers, however, collected
many specimens, which were afterwards bought by Dr. John
Woodward. After his death part of the collection was bought by the
University of Cambridge; the rest was sold by auction “at Mr.
Cooper’s in the Great Piazza, Covent Garden.” Three other early
collectors were John Harwood, D.C.L.; John Bagford, a bookseller,
who seems to have had some knowledge of coins; and Mr. Kemp,
whose collection contained a few London things, especially the two
terra-cotta lamps found on the site of St. Paul’s, which were
supposed to prove the existence of a temple of Diana at that spot.
Burial-places and tombs have been unearthed in various parts of
the City, but all outside the walls of the Roman fortress. Thus, they
have been found on the site of St. Paul’s, in Bow Lane, Queen
Street, Cornhill, St. Dunstan’s Hill, near Carpenter’s Hall, in
Camomile Street near the west end of St. Helen’s Church, in King’s
Street and Ken Street, Southwark—outside Bishopsgate in
“Lollesworth,” afterwards called Spitalfields. The last named was the
most extensive of the ancient cemeteries.
Stow thus describes it:—
“On the East Side of this Churchyard lyeth a large Field, of old
time called Lolesworth, now Spittlefield, which about the Year 1576
was broken up for Clay to make Brick: In the digging whereof many
earthen Pots called Urnæ were found full of Ashes, and burnt Bones
of Men, to wit of the Romans that inhabited here. For it was the
custom of the Romans, to burn their Dead, to put their Ashes in an
Urn, and then to bury the same with certain Ceremonies, in some
Field appointed for that purpose near unto their City.
ROMAN BATH, STRAND LANE
Every of these pots had in them (with the Ashes of the Dead) one
Piece of Copper Money, with the Inscription of the Emperour then
reigning: Some of them were of Claudius, some of Vespasian, some
of Nero, of Antoninus Pius, of Trajanus, and others. Besides those
Urns, many other pots were found in the same place, made of a
white Earth, with long Necks and Handles, like to our Stone Jugs:
these were empty, but seemed to be buried full of some liquid
Matter, long since consumed and soaked through. For there were
found divers Phials, and other fashioned Glasses, some most
cunningly wrought, such as I have not seen the like, and some of
Crystal, all which had Water in them, nothing differing in clearness,
taste, or savour from common Spring Water, whatsoever it was at
the first. Some of these Glasses had Oil in them very thick, and
earthy in savour. Some were supposed to have Balm in them, but
had lost the Virtue: Many of these Pots and Glasses were broken in
cutting of the Clay, so that few were taken up whole.
There were also found divers dishes and cups of a fine red
coloured Earth, which shewed outwardly such a shining smoothness,
as if they had been of Coral. Those had (in the bottoms) Roman
Letters printed, there were also Lamps of white Earth, and red
artificially wrought with divers Antiques about them, some three or
four Images, made of white earth, about a Span long each of them:
One I remember was of Pallas, the rest I have forgotten. I myself
have reserved (amongst divers of those Antiquities there found) one
Urna, with the Ashes and Bones, and one Pot of white Earth very
small, not exceeding the quantity of a quarter of a Wine Pint, made
in shape of a Hare, squatted upon her Legs, and between her Ears is
the mouth of the pot.
There hath also been found (in the same Field) divers Coffins of
Stone, containing the Bones of Men: These I suppose to be the
Burials of some special Persons, in time of the Britons, or Saxons,
after the Romans had left to govern here. Moreover, there were also
found the Skulls and Bones of Men, without Coffins, or rather whose
Coffins (being of great Timber) were consumed.” (Strype, vol. i. bk.
ii. chap. vi.)
The description of all the Roman remains found in London would
take too long. Let us, however, mention some of the more important
(see App. III.).
An undoubted piece of Roman work is the old bath still existing in
Strand Lane. This bath is too small for public use: it belonged to a
private house, built outside London, on the slope of the low hill, then
a grassy field, traversed by half a dozen tiny streams. The bath has
been often pictured.
Many pavements, some of great length and breadth, have been
discovered below the surface: of these some have been taken up;
some have been drawn. More than forty pavements have been found
north of the Thames. These were nearly all on the eastern side of
the Walbrook, that side which has always been marked out as the
original Roman settlement, and many of them were found within the
assumed boundaries of the Roman Prætorium.19
Roman remains have been found under the Tower of Mary-le-Bow
Church, where there was a Roman causeway; in Crooked Lane, in
Clement’s Lane, in King William Street, in Lombard Street, in
Warwick Square, on the site of Leadenhall Market, all along the High
Street, Borough as far as St. George’s Church, in Threadneedle
Street, Leadenhall Street, Fenchurch Street, Birchin Lane, Lime
Street, Lothbury, Gracechurch Street, Eastcheap, Queen Street,
Paternoster Row, Bishopsgate Street Within, and many other places.
Inscribed stones have also been found in Church Street,
Whitechapel, in the Tenter Ground, Goodman’s Fields, Minories, in
the Tower of London, at London Wall near Finsbury Circus, in
Playhouse Yard, Blackfriars, at Pentonville, on Tower Hill, in Nicholas
Lane, Lombard Street, in Hart Street, Crutched Friars.
A figure of a youth carrying a bow was found at Bevis Marks. A
small altar was dug up in making excavations for Goldsmiths’ Hall.
A large number of objects were found in 1837 by dredging the
Thames near London Bridge. They were engraved by the Society of
Antiquaries, and published by Mr. C. Roach Smith in his Illustrations
of Roman London.
Among other objects which he has used in illustration of his book
are pottery, lamps, bronzes, glass, coins, and utensils of various
kinds.
A very interesting figure was discovered in Queen Street in 1842.
It is described by Mr. W. Chaffers in Archæologia, vol. xxx. p. 543:—
“While watching the progress of the excavations recently made in
Queen Street, Cheapside (for the formation of a sewer), I was
fortunately enabled to obtain possession of several rare and curious
specimens of Roman art. A short distance from Watling Street, a fine
piece of Roman wall, running directly across the street, was exposed
to view in a remarkably perfect condition, built of flat red tiles
embedded in solid and compact mortar. Several others, lower down
the street, were also discovered. Within a few yards of the wall, one
of the bricklayers, removing some earth, struck his trowel against
something which he conjectured to be a brass tap; but, on clearing
further, he found it was the right heel of the figure, which lay upon
its face. The height of the figure, if standing erect, would be 15
inches; but in its stooping posture, the perpendicular height from the
base to the crown of the head is only 11 inches. It is evidently
intended to represent a person in the attitude of shooting an arrow
from a bow. The bow and arrow were probably of richer metal than
the figure itself; but no vestiges of them were discovered. The
aperture for the bow is seen in the closed left hand, which held it,
and the bent fingers of the right appear in the act of drawing the
arrow to its full extent previous to its evolation. The eyes are of
silver, with the pupils open; the hair disposed in graceful curls on the
head, as well as on the chin and upper lip. The left hand, which
grasped the bow and sustained the arrow, is so placed as to bring
the latter to a level with the eye; and the steadfast look and
determined expression of the whole face are much heightened by
the silver eyes. It was found at about the depth of between twelve
and thirteen feet.”
In 1825 a small silver figure of Harpocrates was found in the
Thames. It is now in the British Museum.
“Early in December 1877 considerable excavations were made at
Pie Corner,20 over a space about a 100 feet long and 40 feet broad.
At a depth of 11 feet, and at a spot 150 feet, measuring along the
houses, from the middle of the great gateway of the hospital, the
workmen came upon what they took for two great blocks of stone,
which lay half inside the front line of the new building and half under
the footway of the street. Continuing their excavation they found
that the stones were two great coffins lying side by side, close
together. A piece was broken off the lid of each, and in this state,
before their contents had been disturbed at all, they were seen by
Dr. Dyce Duckworth. In the southern sarcophagus was a leaden case
containing a woman’s skeleton. This was disturbed hastily, the
workmen being anxious to secure the lead. The other sarcophagus
contained two skeletons, a man’s and a woman’s. As these had been
somewhat displaced when I saw them half an hour later, I will quote
a note which Dr. Duckworth has kindly written to me as to their
exact position—‘The female faced west (the mediæval ecclesiastical
position), the male faced east (layman’s position).’ The sarcophagi
lay very nearly, but not precisely, east and west.”
A great many Roman remains were found in 1840 on digging for
the foundations of the new Royal Exchange. On the east side of the
area there were fragments showing that older buildings had been
taken away. In the middle there were found thirty-two cesspools, in
some of which were ancient objects. These were cleared out and
filled up with concrete. The soil consisted of vegetable earth,
accumulation and broken remains of various kinds with gravel at the
depth of 16 feet 6 inches. At the western end, however, the
workmen came upon the remains of a small building in situ resting
on the gravel. The walls of the Old Exchange stood upon this
building. When it ceased, oak piles had been driven down and
sleepers laid upon the heads of these piles; a rubble wall was
discovered below the piles, and under the wall was an ancient pit,
sunk 13 feet through the gravel down to the clay.
“The pit was irregular in shape, but it measured about 50 feet
from north to south, and 34 from east to west, and was filled with
hardened mud, in which were contained considerable quantities of
animal and vegetable remains, apparently the discarded refuse of
the inhabitants of the vicinity. In the same depository were also
found very numerous fragments of the red Roman pottery, usually
called Samian ware, pieces of glass vessels, broken terra-cotta
lamps, parts of amphoræ, mortaria, and other articles made of
earth, and all the rubbish which might naturally become
accumulated in a pond in the course of years. In this mass likewise
occurred a number of Imperial Roman coins, several bronze and iron
styles, parts of writing-tables, a bather’s strigil, a large quantity of
caliga-soles, sandals, and remains of leather.” (Sir William Tite.)
The objects taken out of this pit are catalogued and described by
Tite in his volume called Antiquities discovered in Excavating for the
Foundations of the New Royal Exchange.
Roman pottery, found in Ivy Lane and in St. Paul’s Churchyard,
was exhibited at the evening meeting of the L. and Midd. Arch. Soc.,
Sept. 18, 1860.
Roman keys have been found near St. Swithin’s Church, Cannon
Street, at Charing Cross beside the statue of Charles I., beneath
Gerard’s Hall Crypt, and in the Crypt of St. Paul’s while preparing for
the interment of the Duke of Wellington.
ROMAN ANTIQUITIES FOUND IN LONDON, 1786
From Archæologia, vol. viii.
“An important discovery was made in the year 1835 on the
Coleman Street side near the public-house called the Swan’s Nest;
here was laid open a pit or well containing a store of earthen vessels
of various patterns and capacities. This well had been carefully
planked over with thick boards, and at first exhibited no signs of
containing anything besides the native gravelly soil, but at a
considerable depth other contents were revealed. The vases were
placed on their sides longitudinally, and presented the appearance of
having been regularly packed or embedded in the mud or sand,
which had settled so closely round them that a great number were
broken or damaged in being extricated. But those preserved entire,
or nearly so, are of the same material as the handles, necks, and
pieces of the light-brown coloured vessels met with in such profusion
throughout the Roman level in London. Some are of a darker clay
approaching to a bluish black, with borders of reticulated work
running round the upper part, and one of a singularly elegant form
is of a pale-bluish colour with a broad black border at the bottom.
Some are without handles, others have either one or two. Their
capacity for liquids may be stated as varying from one quart to two
gallons, though some that were broken were of much larger
dimensions. A small Samian patera, with the ivy-leaf border, and a
few figured pieces of the same, were found near the bottom of this
well, and also a small brass coin of Allectus, with reverse of the
galley, Virtus Aug., and moreover two iron implements resembling a
boat-hook and a bucket-handle. The latter of these carries such a
homely and modern look, that, had I no further evidence of its
history than the mere assurance of the excavators, I should have
instantly rejected it, from suspicion of its having been brought to the
spot to be palmed off on the unwary; but the fact of these articles
being disinterred in the presence of a trustworthy person in my
employ disarms all doubt of their authenticity. The dimensions of the
pit or well were about 2 feet 9 inches or 3 feet square, and it was
boarded on each side with narrow planks about 2 feet long, and 1½
to 2 inches thick, placed upright, but which framework was
discontinued towards the bottom of the pit, which merged from a
square into an oval form.” (C. Roach Smith in Archæologia, vol.
xxix.)
ROMAN LONDON
x — Sites where Roman pavements and remains have been found.
The dotted lines represent streets added at a later date.
The following is a list of the more important tessellated pavements
which have been discovered in the City:—
STATUETTES OF ROMAN DEITIES
British Museum.
1661. In Scot’s Yard, Bush Lane, with the remains of a large
building. This is supposed to have been an official
residence in the Prætorium. Sent to Gresham College.
1681. Near St. Andrew’s, Holborn—deep down.
” Bush Lane, Cannon Street—deep down.
1707. In Camomile Street—5 feet below the surface, with stone
walls.
1785, 1786. Sherborne Lane. Four pavements were found here.
1786. Birchin Lane, with remains of walls and pottery, at depth of 9
feet, 12 feet, and 13 feet.
1787. Northumberland Avenue and Crutched Friars—12 feet deep.
Society of Antiquaries.
1792. At Poulett House, behind the Navy Pay Office, Great
Winchester Street.
1794. Pancras Lane—11 feet deep.
1803. Leadenhall Street—at depth of 9 feet 6 inches. British
Museum.
1805. Bank of England, the north-west corner. British Museum.
1805. St. Clement’s Church.
1835. Bank of England, opposite Founders’ Court, and St. Margaret,
Lothbury.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com

More Related Content

PDF
Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York
PDF
Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York
PDF
www.webre24h.com - [O`reilly] javascript cookbook - [powers]
PDF
Jquery Cookbook Solutions Examples For Jquery Developers Lindley
PDF
Master Web Design with HTML CSS JavaScript and jQuery Create Stunning Interac...
PDF
w_wile445.pdf
PDF
Get Master Web Design with HTML CSS JavaScript and jQuery Create Stunning Int...
PDF
Special Edition Using Javascript Mcfedries
Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York
Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York
www.webre24h.com - [O`reilly] javascript cookbook - [powers]
Jquery Cookbook Solutions Examples For Jquery Developers Lindley
Master Web Design with HTML CSS JavaScript and jQuery Create Stunning Interac...
w_wile445.pdf
Get Master Web Design with HTML CSS JavaScript and jQuery Create Stunning Int...
Special Edition Using Javascript Mcfedries

Similar to Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York (20)

PDF
Pro jQuery 2 0 Second Edition Adam Freeman
PDF
Jquery In Action Second Edition 2nd Ed Bear Bibeault Yehuda Katz
PPTX
Web Development for Beginners: A Step-by-Step Guide
PDF
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
PDF
Jquery enlightenment
PDF
How To Do Everything With JavaScript
PPTX
Lesson 201 14 sep13-1500-ay
PPTX
Introduction to HTML language Web design.pptx
PDF
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
PDF
Learning Web App Development 1st Edition Semmy Purewal
PDF
Advanced Java Script.pdf
PDF
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
PDF
jQuery for beginners
PDF
Jquery Reference Guide Jonathan Chaffer Karl Swedberg
PDF
Build an App with JavaScript & jQuery
PDF
Special Edition Using Javascript Mcfedries
PDF
Immediate download New Perspectives on HTML5 CSS3 JavaScript 6th Edition Care...
PDF
Wiley.HTML.and.CSS.Oct.2011.pdf
PDF
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
PDF
Html xhtml and css bible 3rd edition
Pro jQuery 2 0 Second Edition Adam Freeman
Jquery In Action Second Edition 2nd Ed Bear Bibeault Yehuda Katz
Web Development for Beginners: A Step-by-Step Guide
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Jquery enlightenment
How To Do Everything With JavaScript
Lesson 201 14 sep13-1500-ay
Introduction to HTML language Web design.pptx
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Learning Web App Development 1st Edition Semmy Purewal
Advanced Java Script.pdf
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
jQuery for beginners
Jquery Reference Guide Jonathan Chaffer Karl Swedberg
Build an App with JavaScript & jQuery
Special Edition Using Javascript Mcfedries
Immediate download New Perspectives on HTML5 CSS3 JavaScript 6th Edition Care...
Wiley.HTML.and.CSS.Oct.2011.pdf
Internet World Wide Web How to Program 2nd Edition Harvey M. Deitel
Html xhtml and css bible 3rd edition
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Lesson notes of climatology university.
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Types and Its function , kingdom of life
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
RMMM.pdf make it easy to upload and study
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
human mycosis Human fungal infections are called human mycosis..pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
TR - Agricultural Crops Production NC III.pdf
Pre independence Education in Inndia.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Lesson notes of climatology university.
FourierSeries-QuestionsWithAnswers(Part-A).pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Types and Its function , kingdom of life
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Anesthesia in Laparoscopic Surgery in India
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
01-Introduction-to-Information-Management.pdf
Cell Structure & Organelles in detailed.
RMMM.pdf make it easy to upload and study
STATICS OF THE RIGID BODIES Hibbelers.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
O5-L3 Freight Transport Ops (International) V1.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Final Presentation General Medicine 03-08-2024.pptx
Ad

Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York

  • 1. Visit https://ebookultra.com to download the full version and explore more ebooks Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York _____ Click the link below to download _____ https://ebookultra.com/download/beginning-javascript- und-css-development-with-jquery-1-ed-edition-richard- york/ Explore and download more ebooks at ebookultra.com
  • 2. Here are some suggested products you might be interested in. Click the link to download Beginning CSS Cascading Style Sheets for Web Design Wrox Beginning Guides 2nd Edition Richard York https://ebookultra.com/download/beginning-css-cascading-style-sheets- for-web-design-wrox-beginning-guides-2nd-edition-richard-york/ Joomla 1 5 JavaScript jQuery 1st Edition Jose Argudo Blanco https://ebookultra.com/download/joomla-1-5-javascript-jquery-1st- edition-jose-argudo-blanco/ Beginning JavaScript 3rd ed Edition Paul Wilton https://ebookultra.com/download/beginning-javascript-3rd-ed-edition- paul-wilton/ Professional XMPP Programming with JavaScript and jQuery 1st Edition Jack Moffitt https://ebookultra.com/download/professional-xmpp-programming-with- javascript-and-jquery-1st-edition-jack-moffitt/
  • 3. Beginning Windows Store Application Development HTML and JavaScript Edition Scott Isaacs https://ebookultra.com/download/beginning-windows-store-application- development-html-and-javascript-edition-scott-isaacs/ Html 5 Black Book Covers Css 3 Javascript Xml Xhtml Ajax Php And Jquery 2Ed 2nd Edition Dt Editorial Services https://ebookultra.com/download/html-5-black-book-covers- css-3-javascript-xml-xhtml-ajax-php-and-jquery-2ed-2nd-edition-dt- editorial-services/ jQuery and JavaScript Phrasebook 1st Edition Brad Dayley https://ebookultra.com/download/jquery-and-javascript-phrasebook-1st- edition-brad-dayley/ Drupal 6 JavaScript and jQuery 1st Edition Matt Butcher https://ebookultra.com/download/drupal-6-javascript-and-jquery-1st- edition-matt-butcher/ Beginning JavaScript 5th Edition Jeremy Mcpeak https://ebookultra.com/download/beginning-javascript-5th-edition- jeremy-mcpeak/
  • 5. Beginning JavaScript und CSS development with jQuery 1. ed Edition Richard York Digital Instant Download Author(s): Richard York ISBN(s): 9780470227794, 0470227796 Edition: 1. ed File Details: PDF, 7.18 MB Year: 2009 Language: english
  • 6. Beginning JavaScript®and CSS Development with jQuery Richard York 27794ffirs.indd 5 3/16/09 3:14:20 PM
  • 7. Beginning JavaScript® and CSS Development with jQuery Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-0-470-22779-4 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 Library of Congress Cataloging-in-Publication Data York, Richard. Beginning JavaScript and CSS development with jQuery / Richard York. p. cm. Includes index. ISBN 978-0-470-22779-4 (paper/website) 1. JavaScript (Computer program language) 2. Web sites--Design. 3. Cascading style sheets. I. Title. QA76.73.J38Y67 2009 006.7’6--dc22 2009005636 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or pro- motional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade- marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. JavaScript is a registered trademark of Sun Microsystems, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. 27794ffirs.indd 6 3/16/09 3:14:20 PM
  • 8. Contents Introduction xix Part I: jQuery API 1 Chapter 1: Introduction to jQuery 3 What Does jQuery Do for Me? 4 Who Develops jQuery? 5 Obtaining jQuery 5 Installing jQuery 5 Programming Conventions 8 XHTML and CSS Conventions 9 JavaScript Conventions 16 Summary 25 Chapter 2: Selecting and Filtering 27 The Origin of the Selectors API 28 Using the Selectors API 29 Filtering a Selection 37 Searching within a Selection with find() 38 Finding an Element’s Siblings with siblings() 39 Selecting Specific Siblings 42 Searching Ancestors Using the parents() and parent() Methods 46 Selecting Children Elements 48 Selecting Elements via What You Don’t Want 50 Selecting a Snippet of the Results 51 Adding More Elements to a Selection 53 Selecting One Specific Element from a Result Set 55 Summary 66 Exercises 66 Chapter 3: Events 69 Assigning an Event with the Traditional Event Model 69 Assigning Events with the W3C Event Model 72 The this Object 73 The event Object 75
  • 9. xii Contents The Microsoft JScript Event Model 77 Creating a Universal Event API 78 Binding Events with jQuery’s bind() Method 80 Binding Events with jQuery’s Event Methods 82 Triggering Events 83 Summary 93 Exercises 93 Chapter 4: Manipulating Content and Attributes 95 Setting and Accessing Attributes 95 Manipulating Class Names 105 Manipulating HTML and Text Content 109 Getting, Setting, and Removing Content 110 Appending and Prepending Content 115 Inserting Beside Content 123 Inserting Beside Content via a Selection 125 Wrapping Content 129 Replacing Elements 146 Removing Content 150 Cloning Content 154 Summary 162 Exercises 163 Chapter 5: Arrays and Iteration 165 Basic Iteration 165 Calling each() Directly 167 Variable Scope 168 Emulating break and continue 170 Iterating a Selection 172 Filtering Selections and Arrays 173 Filtering a Selection 174 Filtering a Selection with a Callback Function 175 Filtering an Array 177 Mapping a Selection or an Array 180 Mapping a Selection 180 Mapping an Array 183 Array Utility Methods 196 Making an Array 197 Finding a Value within an Array 197
  • 10. xiii Contents Merging Two Arrays 198 Removing Duplicate Items 199 Summary 204 Exercises 205 Chapter 6: CSS 207 The css() Method 207 The outerWidth() and outerHeight() Methods 208 Summary 217 Exercises 217 Chapter 7: AJAX 219 Making a Server Request 220 What’s the Difference between GET and POST? 220 Formats Used to Transport Data with an AJAX Request 221 Making a GET Request with jQuery 222 Loading HTML Snippets from the Server 240 Dynamically Loading JavaScript 265 AJAX Events 267 Making an AJAX-Style File Upload 272 Summary 275 Exercises 276 Chapter 8: Effects 277 Showing and Hiding Elements 277 Sliding Elements 279 Fading Elements 280 Custom Animation 281 Summary 283 Exercises 284 Chapter 9: Plugins 285 Writing a Plugin 285 Good Practice for jQuery Plugin Development 295 Summary 296 Exercises 296
  • 11. xiv Contents Part II: jQuery UI 297 Chapter 10: Implementing Drag-and-Drop 299 Making Elements Draggable 300 Making Elements Draggable with Ghosting 308 Dragging between Windows in Safari 311 Delegating Drop Zones for Dragged Elements 314 Summary 326 Exercises 326 Chapter 11: Drag-and-Drop Sorting 327 Making a List Sortable 327 Customizing Sortables 338 Saving the State of Sorted Lists 347 Summary 353 Exercises 354 Chapter 12: Selection by Drawing a Box 355 Introducing the Selectables Plugin 355 Summary 372 Exercises 372 Chapter 13: Accordion UI 373 Building an Accordion UI 373 Setting Auto-Height 376 Changing the Default Pane 377 Toggling the alwaysOpen Option 380 Changing the Accordion Event 380 Filling the Height of the Parent Element 381 Setting the Header Elements 381 Styling Selected Panes 384 Selecting a Content Pane by Location 387 Summary 390 Exercises 391
  • 12. xv Contents Chapter 14: Datepicker 393 Implementing a Datepicker 393 Styling the Datepicker 395 Setting the Range of Allowed Dates 403 Allowing a Date Range to Be Selected 404 Localizing the Datepicker 405 Setting the Date Format 405 Localizing Datepicker Text 406 Changing the Starting Weekday 407 Summary 408 Exercises 408 Chapter 15: Dialogs 409 Implementing a Dialog 409 Examining a Dialog’s Markup 411 Making a Modal Dialog 417 Auto-Opening the Dialog 419 Controlling Dynamic Interaction 420 Animating the Dialog 421 Working with Dialog Events 422 Summary 423 Exercises 424 Chapter 16: Tabs 425 Implementing Tabs 425 Loading Remote Content via AJAX 432 Animating Tab Transitions 436 Summary 437 What Next? 437 Exercises 438 Appendix A: Answers to Exercises 439 Chapter 2 439 Chapter 3 439 Chapter 4 440 Chapter 5 441
  • 13. xvi Contents Chapter 6 441 Chapter 7 442 Chapter 8 442 Chapter 9 443 Chapter 10 443 Chapter 11 444 Chapter 12 444 Chapter 13 444 Chapter 14 445 Chapter 15 445 Chapter 16 445 Appendix B: Selectors Supported by jQuery 447 Appendix C: Selecting and Filtering 451 Appendix D: Events 453 Event Object Normalization 455 Appendix E: Manipulating Attributes and Data Caching 457 Appendix F: Manipulating Content 459 Appendix G: AJAX Methods 461 Appendix H: CSS 465 Appendix I: Utilities 467 Appendix J: Draggables and Droppables 469 Appendix K: Sortables 475 Appendix L: Selectables 479 Notes 480 Appendix M: Effects 481 Speed 481 Callback Function 481
  • 14. xvii Contents Appendix N: Accordion 485 Appendix O: Datepicker 487 Appendix P: Dialog 497 Appendix Q: Tabs 501 Appendix R: Re-Sizables 505 Appendix S: Sliders 509 Index 511
  • 15. Introduction The jQuery JavaScript framework is a rising star in the world of web development. JavaScript frame- works in general have grown to become immensely popular in the past few years in parallel with the ever-increasing presence of JavaScript-driven, so-called Web 2.0 websites that make heavy use of tech- nologies like AJAX and JavaScript in general for slick graphical enhancements that would be impossible or much more cumbersome to incorporate without JavaScript. jQuery’s mission as a JavaScript library is simple — it strives to make the lives of web developers eas- ier by patching over certain portions of cross-browser development and by making other tasks com- monly needed by developers much easier. jQuery has the real, proven ability to reduce many lines of plain-vanilla JavaScript to just a few lines, and, in many cases, just a single line. jQuery strives to remove barriers to JavaScript development by removing redundancy wherever possible and normal- izing cross-browser JavaScript development in key areas where browsers would otherwise differ, such as Microsoft’s Event API and the W3C Event API, and other, more remedial tasks like getting the mouse cursor’s position when an event has taken place. jQuery is a compact, lightweight library that currently works in Microsoft’s Internet Explorer browser from version 6 on, Firefox from version 1.5 on, Safari from version 2.0.2 on, Opera from version 9 on, and Google’s new Chrome browser from version 0.2 on. Getting started with jQuery is very easy — all you have to do is include a single link of markup in your HTML or XHTML documents that includes the library. Throughout this book, I demonstrate jQuery’s API (Application Programming Interface) components in detail and show you how all the nuts and bolts of this framework come together to enable you to rapidly develop client-side applications. I also cover the jQuery UI library, which makes redundant user-interface (UI) tasks on the client side ridiculously easy and accessible to everyday web developers who might not have much JavaScript pro- gramming expertise. Have you ever wanted to create an animated accordion effect like the one found on Apple’s Mac home page at www.apple.com/mac? With jQuery, not only can you create this effect with your own look and feel, but also it’s dead simple to boot. Have you ever wondered how websites make virtual pop-up windows using JavaScript, HTML, and CSS? The jQuery UI library provides the ability to create these pop-up windows and includes the ability to animate transitions like fading the window on and off, or having it re-size from very small to full sized. The jQuery UI library gives you the ability to use animations and transitions using JavaScript, markup, and CSS that you may have thought previously could only have been done with Adobe’s Flash player. The jQuery framework itself has enjoyed a great deal of mainstream exposure. It has been used by Google, Dell, Digg, NBC, CBS, Netflix, The Mozilla Foundation, and the popular WordPress and Drupal PHP frameworks. jQuery is fast — superfast — and it has a small footprint. It’s only 15 KB, using the compressed and gzipped version. 27794flast.indd 19 3/16/09 11:33:36 AM
  • 16. Introduction xx jQuery gives you the ability to provide complex, professional, visually driven user interfaces and effects with very few lines of code. What may have taken other developers days or even weeks to accomplish can be done with jQuery in just a few hours. Who This Book Is For This book is for anyone interested in doing more with less code! You should have a basic understanding of JavaScript. I review some basic JavaScript programming concepts, such as the Event API, but I do not go into great detail about the JavaScript language itself. You’ll want to have at least a basic grasp of the Document Object Model, or DOM, and basic JavaScript programming syntax. Additionally, you’ll need to know your way around CSS and HTML, since knowledge of those technologies is also assumed. A complete beginner might be able to grasp what is taking place in the examples in this book but might not understand certain terminology and programming concepts that would be presented in a beginner’s JavaScript guide, so if you are a beginner and insist with pressing forward, I recommend doing so with a beginning JavaScript book on hand as well. Specifically, I recommend the following Wrox books for more help with the basics: Beginning Web Programming with HTML, XHTML, and CSS ❑ ❑ , 2nd ed. (2008), by Jon Duckett Beginning CSS: Cascading Style Sheets for Web Design ❑ ❑ , 2nd ed. (2007), also written by yours truly. Beginning JavaScript ❑ ❑ , 3rd ed. (2007), by Paul Wilton and Jeremy McPeak For further knowledge of JavaScript above and beyond what is covered in this book, I recommend Professional JavaScript for Web Developers, 2nd ed. (2009), by Nicholas C. Zakas. What This Book Covers This book covers the jQuery JavaScript framework and the jQuery UI JavaScript framework and demon- strates in great detail how to use the jQuery framework to get more results more quickly out of JavaScript programming. I cover each method exposed by jQuery’s API, which contains methods to make common, redundant tasks go much more quickly in less code. Some examples are methods that help you to select elements from a markup document through the DOM and methods that help you to traverse through those selections and filter them using jQuery’s fine-grained controls. This makes working with the DOM easier and more effortless. I also cover how jQuery eliminates certain cross-browser, cross-platform devel- opment headaches like the event model; not only does it eliminate these headaches, but it also makes it easier to work with events by reducing the amount of code that you need to write to attach events. It even gives you the ability to simulate events. Later in the book, I cover how you can leverage the jQuery UI library to make graphically driven UI widgets. jQuery gives you the ability to break content up among multiple tabs in the same page. You have the ability to customize the look and feel of the tabs, and even to create a polished look and feel by providing different effects that come in when you mouse over tabs and click on them. The jQuery UI library also makes it easy to create accordion sidebars, like the one on Apple’s Mac website. These side- bars have two or more panels, and when you mouse over an item, one pane transitions to another via a smooth, seamless animation wherein the preceding pane collapses and the proceeding pane expands. 27794flast.indd 20 3/16/09 11:33:36 AM
  • 17. Introduction xxi The jQuery UI library also gives you the ability to make any element draggable with the mouse; by click- ing and holding and moving the mouse, you can move elements around on a page. It also makes it really easy to create drag-and-drop user interfaces. This can be used to make a dropping zone where you take elements from other parts of the page and drop them in another, as you would in your operating sys- tem’s file manager when you want to move a folder from one place to another. You can also make lists that are sortable via drag-and-drop, rearranging elements based on where you drop them. You can also have a user interface where you drag the mouse cursor to make a selection, as you would in your oper- ating system’s file manager when you want to select more than one file. Then jQuery UI also exposes the ability to re-size elements on a page using the mouse. All of those neat things that you can do on your computer’s desktop, you can also do in a web browser with jQuery UI. jQuery UI also provides a widget for entering a date into a field using a nice, accessible JavaScript- driven calendar that pops up when you click on an input field. You can also make custom pop-up dialogues that are like virtual pop-up windows, except they don’t open a separate browser window — they come up using markup, CSS, and JavaScript. Another widget that jQuery UI provides is a graphical slider bar, similar to your media player’s volume control. As jQuery has done for JavaScript programming in general, jQuery UI strives to do for redundant graphical user interface (GUI) tasks. jQuery UI gives you the ability to make professional user-interface widgets with much less development effort. If you’re interested in reading news about jQuery, how it’s evolving, and topics related to web develop- ment, you may be interested in reading the official jQuery blog at blog.jquery.com, or jQuery’s creator, John Resig’s blog, at www.ejohn.org. If you are in need of help, you can participate in programming discussion at p2p.wrox.com, which you can join for free to ask programming questions in moderated forums. There are also program- ming forums provided by the jQuery community, which you can learn more about at http://docs.jquery.com/Discussion. Finally, I maintain a blog and website at www.deadmarshes.com, where you can contact me directly with your thoughts about the book or read about the web development projects I’m working on. How This Book Is Structured This book is divided into two parts: The first half of the book covers the basic API exposed by the jQuery library, and the second half covers the jQuery UI library. Part 1: jQuery API Chapter 1: Introduction to jQuery ❑ ❑ — In this first chapter, I discuss a little of where jQuery came from and why it was needed. Then I walk you through downloading and creating your first jQuery-enabled JavaScript. 27794flast.indd 21 3/16/09 11:33:36 AM
  • 18. Introduction xxii Chapter 2: Selecting and Filtering ❑ ❑ — This chapter introduces jQuery’s selector engine, which uses selectors like you will have used with CSS to make selections from the DOM. Then I talk about the various methods that jQuery exposes for working with a selection, to give you fine- grained control over what elements you’re working with from the DOM. I talk about methods that let you select, ancestor elements, parent elements, sibling elements, descendent elements, how to remove elements from a selection, how to add elements to a selection, and how to reduce a selection to a specific subset of elements. Chapter 3: Events ❑ ❑ — In this chapter, I begin by reviewing the event model as you find it in plain- vanilla JavaScript. You have the traditional event model, the W3C’s event model, and Microsoft’s event model. I discuss the differences between these and why jQuery needed an entirely new Event API to make the situation easier for web developers. Then I present jQuery’s Event API and how you use it. Chapter 4: Manipulating Content and Attributes ❑ ❑ — In Chapter 4, you learn how to use the methods that jQuery exposes for working with content, text and HTML, and element attributes. jQuery provides methods for doing just about everything you’d want to do to an element. Chapter 5: Arrays and Iteration ❑ ❑ — In Chapter 5, I talk about how you can enumerate over a selection of elements or an array using jQuery. As with everything else, jQuery provides an eas- ier way that requires fewer lines of code to loop over the contents of an array or a selection of elements from the DOM. Chapter 6: CSS ❑ ❑ — In this chapter, you learn about the methods that jQuery exposes for working with CSS properties and declarations. jQuery provides intuitive and versatile methods that let you manipulate CSS in a variety of ways. Chapter 7: AJAX ❑ ❑ — Chapter 7 elaborates on the methods that jQuery exposes for making AJAX requests from a server, which allows you to request server content without working directly with the XMLHttpRequest object and supports handling server responses in a variety of formats. Chapter 8: Effects ❑ ❑ — In Chapter 8, I discuss some helper methods that jQuery exposes for dis- covering what browser and browser version you’re working with, whether you’re working with a browser that supports the standard W3C box model for CSS, and a variety of odds and ends methods for working with objects, arrays, functions, and strings. Chapter 9: Plugins ❑ ❑ — In this chapter, I describe how you can make your own plugins for jQuery. Part II: jQuery UI Chapter 10: Implementing Drag-and-Drop ❑ ❑ — In Chapter 10, I begin my coverage of the jQuery UI library by discussing how you make individual elements draggable and how you make a drag-and-drop interface where you take one element and place it on top of another to create a complete drag-and-drop sequence. Chapter 11: Drag-and-Drop Sorting ❑ ❑ — In Chapter 11, I discuss how you make lists sortable using drag-and-drop. Chapter 12: Selection by Drawing a Box ❑ ❑ — In Chapter 12, I cover the portion of the jQuery UI library that lets you make a selection by drawing a box with your mouse, just like you would do in your OS’s file management application. Chapter 13: Accordion UI ❑ ❑ — In this chapter, I discuss how to make a really neat, polished-looking sidebar that has panes that transition like an accordion. When you mouse over an element, one pane collapses via a slick animation, and another one expands, also via an animation. 27794flast.indd 22 3/16/09 11:33:36 AM
  • 19. Introduction xxiii Chapter 14: Datepicker ❑ ❑ — In Chapter 14, I cover how you make a standard form input field into a Datepicker, using jQuery’s Datepicker widget. Chapter 15: Dialogs ❑ ❑ — In Chapter 15, I talk about how you create virtual pop-up windows, using the jQuery UI library, that look and act like real pop-up windows but are entirely con- tained in the same web page that launches them and are built using pure markup, CSS, and JavaScript. Chapter 16: Tabs ❑ ❑ — In Chapter 16, I discuss the jQuery UI tab component, which allows you to take a document and split it into several tabs and navigate between those tabs without needing to load another page. Appendixes ❑ ❑ — Appendix A contains the answers to chapter exercises. Appendix B through Appendix S contain reference materials for jQuery and jQuery UI. What You Need to Use This Book To make use of the examples in this book, you need the following: Several Internet browsers to test your web pages ❑ ❑ Text-editing software or your favorite IDE ❑ ❑ Designing content for websites requires being able to reach more than one type of audience. Some of your audience may be using different operating systems or different browsers other than those you have installed on your computer. This book focuses on the most popular browsers available at the time of this writing as supported: Microsoft Internet Explorer 6 or newer for Windows ❑ ❑ Safari for Mac OS X, version 2 or newer ❑ ❑ Mozilla Firefox for Mac OS X, Windows, or Linux ❑ ❑ Opera for Mac OS X, Windows and Linux, version 9 or newer ❑ ❑ Conventions To help you get the most from the text and keep track of what’s happening, I’ve used a number of con- ventions throughout the book. First, be aware that not all the figures referenced in the text actually appear in print. This means, for example, that the screenshots that actually do appear in a chapter might not be numbered in strict sequence. For example, if you look only at the screenshots in Chapter 3, the first is Figure 3-1, and the second is Figure 3-3. There is a reference to Figure 3-2 in the text, but the actual screenshot is not printed. These “missing” screenshots aren’t really missing, though — they are generated by the code download. It’s just that for all intents and purposes, they are identical to the screenshots that are printed before or after them and are therefore not needed in the text. 27794flast.indd 23 3/16/09 11:33:36 AM
  • 20. Introduction xxiv Try It Out The Try It Out is an exercise you should work through, following the text in the book. 1. It usually consists of a set of steps. 2. Each step has a number. 3. Follow the steps through with your copy of the database. Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text. Notes, tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this. As for styles in the text: We ❑ ❑ highlight with italics new terms and important words when we introduce them. We show keyboard strokes like this: ❑ ❑ Ctrl+A. We show URLs and code within the text like so: ❑ ❑ persistence.properties. We present code in the following way: ❑ ❑ We use a monofont type with no highlighting for most code examples. Also, Visual Studio’s code editor provides a rich color scheme to indicate various parts of code syntax. That’s a great tool to help you learn language features in the editor and to help prevent mistakes as you code. To reinforce Visual Studio’s colors, the code listings in this book are colorized using colors similar to what you would see on screen in Visual Studio working with the book’s code. In order to optimize print clarity, some colors have a slightly different hue in print from what you see on screen. But all of the colors for the code in this book should be close enough to the default Visual Studio colors to give you an accurate representation of the colors. Source Code As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is avail- able for download at www.wrox.com. Once at the site, simply locate the book’s title (either by using the Search box or by using one of the title lists) and click on the Download Code link on the book’s detail page to obtain all the source code for the book. Because many books have similar titles, you may find it easiest to search by ISBN; this book’s ISBN is 978-0-470-22779-4. Once you download the code, just decompress it with your favorite compression tool. Alternatively, you can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to see the code available for this book and all other Wrox books. 27794flast.indd 24 3/16/09 11:33:36 AM
  • 21. Introduction xxv Errata We make every effort to ensure that there are no errors in the text or in the code. However, no one is perfect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty piece of code, we would be very grateful for your feedback. By sending in errata you may save another reader hours of frustration, and at the same time, you will be helping us provide even higher quality information. To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or one of the title lists. Then, on the Book Search Results page, click on the Errata link. On this page, you can view all errata that have been submitted for this book and posted by Wrox editors. A complete book list including links to errata is also available at www.wrox.com/misc-pages/booklist.shtml. If you don’t spot “your” error on the Errata page, click on the Errata Form link and complete the form to send us the error you have found. We’ll check the information and, if appropriate, post a message to the book’s Errata page and fix the problem in subsequent editions of the book. p2p.wrox.com For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based sys- tem for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e‑mail you topics of interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry experts, and your fellow readers are present on these forums. At http://p2p.wrox.com, you will find several different forums that will help you not only as you read this book, but also as you develop your own applications. To join the forums, just follow these steps: 1. Go to p2p.wrox.com and click on the Register link. 2. Read the terms of use and click Agree. 3. Complete the required information to join as well as any optional information you wish to pro- vide and click Submit. 4. You will receive an e‑mail with information describing how to verify your account and com- plete the joining process. You can read messages in the forums without joining P2P, but in order to post your own messages, you must join. Once you join, you can post new messages and respond to messages other users post. You can read messages at any time on the Web. If you would like to have new messages from a particular forum e‑mailed to you, click on the “Subscribe to this Forum” icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques- tions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page. 27794flast.indd 25 3/16/09 11:33:36 AM
  • 22. Part I jQuery API Chapter 1: Introduction to jQuery Chapter 2: Selecting and Filtering Chapter 3: Events Chapter 4: Manipulating Content and Attributes Chapter 5: Arrays and Iteration Chapter 6: CSS Chapter 7: AJAX Chapter 8: Effects Chapter 9: Plugins
  • 23. 1 Introduction to jQuery JavaScript frameworks have arisen as necessary and useful companions for client-side web devel- opment. Without JavaScript frameworks, client-side programming becomes a crater-filled mine- field of cross-browser, cross-platform inconsistencies and idiosyncrasies. JavaScript frameworks pave over those craters and inconsistencies to create a seamless, enjoyable client-side program- ming experience. The most important hole filled by a JavaScript framework is inconsistencies between Internet Explorer’s and the W3C’s standard Event APIs. jQuery fills in this hole by making a cross-browser Event API that is very similar to the W3C’s, adding some original helpful extensions of its own. Another hole filled by most of the popular client-side JavaScript frameworks is the ability to select and traverse through nodes in the Document Object Model (DOM) using more than the very reme- dial selection and traversal APIs that are provided by browsers’ default DOM implementations. jQuery provides a selection mechanism that uses selector syntax like that used in cascading style sheets. However, not content to support only the standard selectors supported in CSS and even the new Selectors API implementations supported by WebKit and Internet Explorer 8, jQuery again extends the standard to support new, innovative, and useful selectors that make sense when using selectors to select DOM nodes. In a nutshell, jQuery reduces significantly the amount of JavaScript programming and Q/A (qual- ity assurance) you have to undertake. It takes what might take several lines of code to write, and more often than not reduces that to just one or a few lines of code. jQuery makes your JavaScript more intuitive and easier to understand. jQuery takes JavaScript programming (which at one time had a higher barrier of entry due to complexity and cross-browser, cross-platform idiosyncrasies) and makes it easier and more attractive to average web developers. Throughout this book, I will discuss jQuery’s Application Programming Interface, or API. We’ll look in depth and up close at each little bit of programming syntax that enables jQuery to do what it does. With each new bit, I also provide simple, to-the-point examples that demonstrate how that bit works. I show you how to write JavaScript applications using jQuery, and by the end of this book, you too will be able to create Web 2.0 applications that function seamlessly across multiple browsers and platforms.
  • 24. 4 Part I: jQuery API In this chapter, I begin discussion of jQuery by introducing what you get out of jQuery, who develops jQuery, how you obtain jQuery, and how you install jQuery and test that it is ready to use. As I mentioned in the Introduction, I do not assume that you are a JavaScript expert in this book, but I do assume that you are familiar with basic JavaScript concepts, such as the DOM and attaching events. I will do my best to keep examples simple and to the point and avoid layering on thick programming jargon. What Does jQuery Do for Me? jQuery makes many tasks easier. Its simplistic, comprehensive API has the ability to completely change the way you write JavaScript, with the aim of consolidating and eliminating as many common and redundant tasks as possible. jQuery really shines in the following areas: jQuery makes iterating and traversing the DOM much easier via its various built-in methods for ❑ ❑ doing the same. jQuery makes selecting items from the DOM easier via its sophisticated, built-in ability to use ❑ ❑ selectors, just like you would use in CSS. jQuery makes it really easy to add your own custom methods via its simple-to-understand ❑ ❑ plug-in architecture. jQuery helps reduce redundancy in navigation and UI functionality, like tabs, CSS and markup- ❑ ❑ based pop-up dialogues, animations, and transitions, and lots of other things. jQuery won’t do your laundry, walk the dog, or broker world peace (yet), but it does bring a lot to the table in terms of making client-side website development easier. Is jQuery the only JavaScript framework? — no, certainly not. You can pick from several JavaScript frameworks: base2, Yahoo UI, Prototype, SproutCore, Dojo, and so on. I picked jQuery for this book simply because I enjoy its simplicity and lack of verbosity. On the other hand, among the other frame- works, you’ll find that there is a lot of similarity and each provides its own advantages in terms of uni- fying Event APIs, providing sophisticated selector and traversal implementations, and providing simple interfaces for redundant JavaScript-driven UI tasks. In the past, I’ve been a big fan of base2, simply for its commitment to supporting W3C-sanctioned and de facto standard APIs seamlessly. But I have decided to focus on jQuery exclusively and exhaustively for this book because I think its popularity merits comprehensive coverage, which I’m able to present in a way that is more befitting novice programmers. In a nutshell, jQuery blurs and even erases lines in some places that existed as barriers for true cross- browser, cross-platform development. It gives you a standard Event API, a standard Selectors API, use- ful traversal and enumeration methods, and a very useful UI library that work across the board in Internet Explorer, Safari, Firefox, and Opera on Windows, Mac, and Linux platforms. That’s not to say that you won’t ever encounter cross-browser issues with your programs, but jQuery makes it much less likely and eliminates a hefty chunk of compatibility issues.
  • 25. 5 Chapter 1: Introduction to jQuery Who Develops jQuery? I won’t spend a lot of time talking about the history of JavaScript frameworks, why they exist, and so on. I prefer to get straight to the point. That said, a brief mention of the people involved with developing jQuery is in order. jQuery’s lead developer and creator is John Resig, whose website is located at www.ejohn.org. John resides in Boston, Massachusetts and is a JavaScript Evangelist for the Mozilla Corporation. There are also several other people who have contributed to jQuery and continue to assist with its development. You can learn more about these people and what roles they played in jQuery’s develop- ment at http://docs.jquery.com/About/Contributors. Obtaining jQuery jQuery is a free, Open Source JavaScript Framework. The current stable, production release version, as of this writing, is 1.2.6. I use version 1.2.6 throughout the course of this book. Getting jQuery is easy — all you have to do is go to www.jquery.com and click on the “Download” link. You’ll see three options for downloading: a packed and gzipped version, an uncompressed version, and a packed version; these all refer to the same jQuery script. Download “uncompressed” if you want to be able to look at jQuery’s source code. Download “packed” if you, for whatever reason, are unable to use gzip compression. The packed version is the same JavaScript code minus all comments, white space, and line breaks. Otherwise, for the best possible download performance, the packed and gzipped version is the best. Installing jQuery Throughout this book, I will refer to the jQuery script as though it is installed at the following path: www.example.com/Library/jquery/jquery.js. Therefore, if I were using the domain example.com, jQuery would have this path from the document root, /Source Code/jquery/jquery.js. You do not have to install jQuery at this exact path. The following “Try It Out” assists you with installing jQuery by giving you an alternative dialogue when the script is properly installed. Try It Out Installing and Testing jQuery Example 1-1 To install and test jQuery, follow these steps. 1. Download the jQuery script from www.jquery.com. Alternatively, I have also provided the jQuery script in this book’s source code download materials available for free from www.wrox.com. 2. Enter the following XHTML document, and save the document as Example 1-1.html. Adjust your path to jQuery appropriately; the path that I use reflects the path needed for the example to
  • 26. 6 Part I: jQuery API work when opened in a browser via the source code materials download made available for this book from www.wrox.com. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd”> <html xmlns=’http://www.w3.org/1999/xhtml’ xml:lang=’en’> <head> <meta http-equiv=’content-type’ content=’text/html; charset=utf-8’ /> <meta http-equiv=’content-language’ content=’en-us’ /> <title>Link</title> <script type=’text/javascript’ src=’../../../Source Code/jQuery/jQuery.js’> </script> <script type=’text/javascript’ src=’Example 1-1.js’></script> <link type=’text/css’ href=’Example 1-1.css’ rel=’stylesheet’ /> </head> <body> <p> jQuery is not loaded. </p> </body> </html> 3. Enter the following JavaScript document, and save the document as Example 1-1.js: if ($) { $(document).ready( function() { $(‘p’).addClass(‘tmpFrameworkLoaded’); $(‘p’).text(‘jQuery successfully loaded and running!’); } ); } 4. Enter the following CSS document, and save the document as Example 1-1.css: body { font: 16px sans-serif; } p { color: red; border: 1px solid red; padding: 5px; margin: 5px; } p.tmpFrameworkLoaded { color: green; border: 1px solid green; } The preceding code results in the screenshot that you see in Figure 1-1, if the installation was unsuc- cessful; and the screenshot in Figure 1-2, if the installation was successful.
  • 27. 7 Chapter 1: Introduction to jQuery Figure 1-1 Figure 1-2 In the preceding example, you installed and tested your installation of the jQuery framework. The XHTML document references a style sheet and a test JavaScript. The XHTML document contains just a single <p> element that contains the text “jQuery is not loaded.” The style sheet has a rule that makes that text red with a red border around the <p> element. The JavaScript that you included first looks for the jQuery object, which is contained in a single dollar sign. That one dollar sign contains all of jQuery’s functionality, which makes jQuery statements really short. If that’s too short for you, you can also substitute “jQuery” for the dollar sign, which would have made that JavaScript example look like this: if (jQuery) { jQuery(document).ready( function() { jQuery(‘p’).addClass(‘tmpFrameworkLoaded’); jQuery(‘p’).text(‘jQuery successfully loaded and running!’); } ); }
  • 28. 8 Part I: jQuery API An event is attached to jQuery’s ready event, which is executed as soon as the DOM is fully loaded, or all markup content, JavaScript and CSS, but not images. In old-time JavaScript, you would have made your JavaScript execute at page load, or the onload event. The onload event can be much slower, how- ever, since it waits for all content and images to load before executing, instead of just content. With an event attached to the ready event, you’re ready to do something with the document. In this case, once the document is loaded, jQuery selects the <p> element and gives it the class name tmpFramework​ Loaded. Then jQuery selects the <p> element again and changes its text content to say “jQuery successfully loaded and running!” The addition of the class name results in the <p> element having green text with a green border around the element. The preceding is a pretty simple, cut-and-dry test of jQuery’s existence, and with this simple example, you see a huge difference with traditional, framework-less JavaScript. Without the jQuery framework, this is what the preceding example would have looked like: window.onload = function() { var $p = document.getElementsByTagName(‘p’)[0]; $p.className = ‘tmpFrameworkLoaded’; if ($p.innerText) { $p.innerText = ‘jQuery successfully loaded and running!’; } else { $p.textContent = ‘jQuery successfully loaded and running!’; } }; Programming Conventions In web development, it’s common for professional web designers, web developers — and anyone with a job title whose day-to-day activities encompass the maintenance of source code — to adopt standards and conventions with regard to how the source code is written. Standardization bodies like the W3C, who define the languages that you use to create websites, already decide on some standards for you. Some standards are not written, but are rather de facto standards. De facto standards are standards that have become accepted throughout the industry, despite not appearing in any official document developed by a standards organization. Throughout this book, I talk about standards, de facto and official, and how to develop and design web- based documents and even web-based applications that take those standards into account. For example, I talk extensively about how to separate behavior (JavaScript) from presentation (CSS) and structure (XHTML). JavaScript written in this way is commonly referred to as non-intrusive JavaScript — it’s non- intrusive because it supplements the content of a web document, and, were it turned off, the document would still be functional. CSS is used to handle all the presentational aspects of the document. And the structure of the document lives in semantically written XHTML. XHTML that is semantically written is organized meaningfully with the right markup elements and contains very little, if any at all, presenta- tional components directly in the markup.
  • 29. 9 Chapter 1: Introduction to jQuery In addition to standards, I discuss how to develop web-based documents, taking into account different browser inconsistencies, discrepancies, and idiosyncrasies. There is some interactive functionality that nearly every browser handles differently; in those situations, other web professionals have already pio- neered de facto standards that are used to bring all browsers into accord. The idea of a JavaScript foun- dational framework has become more popular and increasingly a dependency for so-called Web 2.0 applications, like the ones you’ll learn to develop using the jQuery framework. Before I begin the discussion of jQuery, in the coming sections, I provide a generalized overview of pro- gramming conventions and good practice that should be followed. XHTML and CSS Conventions It’s important that your web documents be well-organized, cleanly written, and appropriately named and stored. This requires discipline and even an obsessive attention to the tiniest of details. The following is a list of rules to abide by when creating XHTML and CSS documents: Catch errors in XHTML and CSS. ❑ ❑ When selecting ID and Class names, make sure that they are descriptive and are contained in a ❑ ❑ namespace. You never know when you might need to combine one project with another — name­ spaces will help you to prevent conflicts. When defining CSS, avoid using generic type selectors. Make your CSS more specific. This will ❑ ❑ also help with preventing conflicts. Organize your files in a coherent manner. Group files from the same project in the same folder; ❑ ❑ separate multiple projects with multiple folders. Avoid creating huge file dumps that make it difficult to locate and associate files. Avoid inaccessible markup. Stay away from frames, where possible. Organize your markup ❑ ❑ using semantically appropriate elements. Place paragraphs in <p> elements. Place lists in <ul> or <ol> elements. Use <h1> through <h6> for headings, and so on. If you are able to, also consider the loading efficiency of your documents. For development, use ❑ ❑ small, modularized files organized by the component; combine and compress those modular- ized files for a live production site. In the following sections, I present some examples of why the preceding list of rules is important. Catching Errors in XHTML and CSS There are certain times when you won’t be able to easily spot markup or style errors. More often than not, getting into a routine of indenting and spacing markup documents and style sheets will make it much easier to spot errors during the initial development of a document, and much easier to perform ongoing maintenance. However, neat and tidy development of a document isn’t always an option. Maybe you’ve inherited an old content management system or have to deal with some other piece of software that generates your source code for you. Next I’ll talk about what you can do to more easily detect and repair errors.
  • 30. 10 Part I: jQuery API Markup Errors in XHTML and HTML Markup errors typically come about from simple human error. You may forget to type in a closing tag for an element. You may forget to encode certain special characters. You may use an ID name more than once in a document by mistake. If a web document contains errors, the browser may carry on as if everything is just fine and dandy, and it may not be obvious that it contains errors. Some errors go undetected because browsers are designed to handle errors in HTML as they are found. The browser decides what to do with an error when it comes to it and then simply moves on with processing the HTML document. (For example, it may be able to guess where a closing tag is supposed to be.) When an error is found, the browser tries to continue on and display a document to the end-user, and more often than not, it succeeds. In some cases, you may notice a visual glitch and see clearly that something is out of place, but it’s also possible that something not so obvious has been affected by the error. For example, you may try attach- ing an event with JavaScript, and the event doesn’t fire. You may try manipulating the document with script by removing or inserting elements and find that the elements aren’t being inserted, or are being inserted in the wrong place. The effects of markup errors like this are much more subtle. Markup errors do not appear in your browser’s error console. The only place where a structural markup error will show up is in a validation of the document using the W3C’s markup validation service located at http://validator.w3.org. XHTML, on the other hand, is not forgiving of markup errors, and assuming that the browser properly supports XHTML, the browser won’t attempt any kind of error correction when it encounters an error in an XHTML document. One type of markup error that will bring processing to a halt is an incorrectly specified MIME (Multipurpose Internet Mail Extensions) type. The MIME standard is used by browsers and Web Servers to facilitate the automatic identification and handling of files, which is to say that a MIME type is part of what a browser uses to identify the con- tents of a document. XHTML documents are supposed to be served with an application/xhtml+xml MIME type. The following is one way of setting the MIME type for an XHTML document: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> <html xmlns=’http://www.w3.org/1999/xhtml’ xml:lang=’en’> <head> <meta http-equiv=’Content-Type’ content=’application/xhtml+xml; charset=UTF-8’ /> </head> <body> In the preceding code example, the XHTML MIME type is set using a <meta /> element that’s included in the document headers. The http-equiv attribute included in a <meta /> element is used to set HTTP headers within the markup document itself. In the preceding code example, the Content-Type HTTP header is being set, which, when supported by the browser, will force the browser to interpret an XHTML document as application/xhtml+xml, rather than text/html. An XHTML document properly served with the application/xhtml+xml MIME type with markup errors like mismatched tags, or missing tags, or any markup error of any kind will result in what’s commonly called the XML yellow screen of death (YSOD). The name yellow screen of death was coined because Mozilla’s (and later, Firefox’s) XML error messages appear against a yellow background, and XML error messages
  • 31. 11 Chapter 1: Introduction to jQuery prevent the display of the document, which prevents the user from seeing a web page, hence the “death” part. Of course, the XML/XHTML error message isn’t yellow in every browser, but the point is that, in properly served XHTML, one error could make a document unviewable by the end-user. The yellow screen of death is also related to another error message, the blue screen of death, which, of course, is the de facto name for error messages in the Windows Operating System that result in a complete system crash — at the time of the crash, an error message with white lettering on a blue screen is seen. XHTML 1.0 documents are not typically served with the correct, intended MIME type. Rather, they are usually served as an HTML document — which isn’t techni- cally illegal, as long as they are XHTML 1.0 documents. XHTML 1.1, on the other hand, must be served as application/xhtml+xml. It’s a good idea, if you’re going the XHTML route, to properly serve the document with the application/xhtml+xml MIME type. Setting the XHTML MIME type is the best, most compatible approach, since browsers like IE that don’t understand the XHTML MIME type will carry on and inter- pret the document as plain-old HTML, while Firefox, Safari, and the like will correctly interpret the XHTML document. If errors are present, these browsers won’t show a rendered document but, rather, will show an error message complaining that something is awry in the document. If you’re going the XHTML route, keeping the document neat becomes a matter of keeping the document maintainable, and thus a matter of personal preference. Typically, dynamic websites strip the markup source of excess white space in order to reduce the size of the document for performance advantages, and even in the age of ubiquitous broadband connections, it’s still a good idea to optimize a document for very slow dial-up connections, which are still in widespread use in rural areas. Dynamic websites typically also have the best of both worlds in place. That is to say, on a pre-production server, the website may serve uncompressed markup, while on a production server, the website serves compressed markup. For your own sanity as a programmer, I strongly recommend that you maintain neat and organized markup, check your markup documents for validation errors using the W3C validation service, and consider using XHTML. Ultimately, however, XHTML or HTML is a matter of personal preference. Both are perfectly acceptable Internet standards for the creation of web documents. The examples in this book use the XHTML standard — however, these examples will work equally well with the HTML standard. Errors in CSS Errors in style sheets usually make themselves known by not displaying the style you applied. However, errors in CSS can also be more subtle and difficult to spot. To catch errors in CSS, I recom- mend one of the two following approaches: Use Mozilla Firefox (or another browser that reports CSS errors), and look for CSS errors in the ❑ ❑ browser’s Error Console. In Firefox, that’s located in Tools?Error Console. Use the W3C’s CSS validation service at ❑ ❑ http://jigsaw.w3.org/css-validator. Either of these solutions will assist you in locating and extinguishing style-sheet errors.
  • 32. 12 Part I: jQuery API It’s also good practice to get into the habit of writing neat and organized CSS. Indent your style sheets with white space, and use line breaks to make the style sheets more maintainable. The browser doesn’t care what your style sheet looks like, as long as the basic syntax is correct. You may add or remove white space to your heart’s content. I continue to revisit the topics of neat and organized source code throughout this book by way of example. ID and Class Naming Conventions Most web developers don’t think too much about the topics of namespacing and naming conventions. Naming conventions are just as important in your markup ID and class names as namespacing is impor- tant in programming languages. First, what is namespacing, and why do you need to do it? Namespacing is the concept of making your programs, source code, and so on tailored to a particular naming convention, in an effort to make your programs more portable and more capable of living in diverse, foreign programming environments. In other words, if you want to be able to directly insert a web application into your document, you want to be sure that the class and ID names, style sheets and script, and all the bits that make your web applica- tion what it is do not conflict with any applications that are already present in the document. Your appli- cations should be fully self-contained and self-sufficient and not collide or conflict with any elements already present in a document. What are some common ID names that people use in style sheets? Think first about what the typical components of a web application are. There’s a body. There may be one or more columns. There may be a header and a footer, and there are lots of components that can potentially be identified as generic, redundant pieces that all web applications may have. Then, it stands to reason that plenty of websites are probably using ID and class names like body, header, footer, column, left, right, and the like. If you name an element with the ID or class name body, you have a very good chance of conflicting with an overwhelming majority of websites in existence today. To avoid this type of conflict, it’s considered good practice to prefix ID and class names within a web application to avoid conflicts and namespace collisions. If you write an application called tagger, you might namespace that application by prefixing all of your ID and class names with the word tagger. For example, you might have taggerBody, tagger​ Header, taggerFooter, and so on. It may be possible, however, that someone has already written an application called tagger. To be safe, you might do a Web search on the name you’ve chosen for your application to make sure that no one’s already using that name. Typically, simply prefixing your ID and class names with your application’s name is enough. Additionally, it also helps to prefix ID and class names with type selectors in style sheets. Type selectors help you narrow down what to look for when modifying or maintaining a document. For example, the ID selector #thisID is ambiguous. You don’t know what kind of element thisID is, and thus would likely have to scan the entire document to find it. But div#thisID is more specific. By including the div in the selector, you instantly know you’re looking for a <div> element. Including the type in the selector also helps you in another way: When dealing with class names, you can have the same class name applied to different types of elements. While I may not condone that as good practice, at least in the style sheet, you can control which element gets which style. span.someClass and div.someClass are selectors that dif- ferentiate style based on the type of element, whereas .someClass is more ambiguous and applies to any element. ID and class names should also be descriptive of their purpose in a semantically meaningful way. Keep in mind that an ID name can potentially be used in a URL as an HTML anchor. Which is better:
  • 33. 13 Chapter 1: Introduction to jQuery www.example.com/index.html#left or www.example.com/index.html#exRelatedDocuments? The lat- ter ID anchor is namespaced ex for example.com, and RelatedDocuments is the name of the element; thus, the latter URL includes more information about what purpose the element serves and greatly increases the maintainability of the document in a very intuitive way. Additionally, the latter has more benefit in terms of search engine optimization (SEO). The former is too ambiguous and won’t provide much in the way of SEO. Think of each of your ID and class names as though it is part of the URL of your document. Give each ID and class name that you create semantic names that convey meaning and purpose. Generic Type Selectors Generic type selectors are style-sheet rules that look something like this: a { color: #29629E; } In the preceding style-sheet rule, you see what’s probably a pretty common scenario, changing the color of every link in a document via a generic type selector that refers to all <a> elements. Generic type selec- tors should be avoided for the same reason that it is good to namespace ID and class names within a document, avoiding conflicts when multiple scripts or style sheets are combined in the same document. Instead, it’s best practice to apply ID or class names to these elements, or at the very least, place them in a container that has an ID or class name, and only use descendent selectors when referencing those ele- ments via a style sheet. div#tmpBanner a { color: #29629E; } The preceding example avoids the pitfalls introduced by using a blanket, generic selector style-sheet rule by limiting the scope of the style-sheet rule’s application. Now, only <a> elements that are descen- dants of a <div> with the ID name tmpBanner will receive the declaration color: #29629E;. Storing and Organizing Files How files are organized and stored is important to the maintainability of a document. You should main- tain your documents in an easy-to-understand, easy-to-learn directory hierarchy. Different people have different approaches to storing and organizing files, obviously. What matters is that there is an organiza- tion scheme, rather than none at all. Some choose to store documents by type and then separate them by application, while others prefer to separate by application first, then sort by type. Avoid Making Documents Inaccessible Accessibility is also an important factor to consider in the design of a web document. You should do your best to make your JavaScript non-intrusive, but also avoid taking away a document’s accessibility by either script or markup. Avoid using frames. ❑ ❑ Limit the number of images to those that actually contribute to the content of a document (as ❑ ❑ opposed to the design). Try to contain as much of the design as possible in CSS background
  • 34. 14 Part I: jQuery API images, and keep images that contribute to the content in <img /> elements. Be sure to include alt attributes that describe the image for each <img /> element. Place content in semantically appropriate markup containers — use ❑ ❑ <p> for paragraphs, <h1> through <h6> for headings, for example. Make the design high contrast. Imagine what the document would look like in black and white ❑ ❑ through the eyes of someone with poor vision. Can you easily read the content? Avoid wandering too far away from established user-interface conventions. Can you distinguish ❑ ❑ hyperlinks from normal content? Make the content keyboard-accessible. Can you navigate without a pointing device? ❑ ❑ Make the content unobtrusive. Can you use the website without flash and JavaScript functional- ❑ ❑ ity? JavaScript and flash should enhance web content in a complementary way, not be a requirement. Avoid placing a large number of links at the beginning of every document. If you were listening ❑ ❑ to the content being read to you, rather than seeing it visually, would the experience be enjoyable? Accessibility should be practiced to the point of becoming an automatic reflex. It should be cemented in your development practices in a fundamental way in the same way that namespacing, file organization, and validation are; but while other best practices can become second nature easily, it’s also very easy to get into the habit of ignoring accessibility, so a conscious effort must be made to periodically review accessibility and ingrain accessibility in the development process. Efficiency in Markup and CSS Markup and CSS in a complex website can easily become large and bloated and drag down overall load- ing and execution times more and more. This can become particularly troublesome as the overall popu- larity of a site increases. As the complexity of a website increases, it becomes necessary to look into ways of streamlining the content. It’s best to limit the number of external files being loaded, but all CSS and JavaScript should be included in at least one external file. Were JavaScript and CSS included directly in a document, the initial loading time would improve, but you’d also lose the advantage of caching JavaScript and CSS on the client side. For the best of the best in efficiency, combine the following concepts: Server-side gzip compression ❑ ❑ Client-side caching ❑ ❑ Automatic compression of markup content ❑ ❑ Automatic compression and consolidation of multiple CSS and JavaScript files ❑ ❑ When the preceding items are combined, you make the loading times of a web document the best pos- sible; however, there are some caveats to consider that may at first seem contradictory: Maintainable markup should be written in a neat and organized manner. It should be well- ❑ ❑ spaced and indented and contain line breaks where appropriate. Good programming practice means modularized development, so break up your CSS and ❑ ❑ JavaScript by component and application. Make small, easy-to-digest chunks. This will speed up your ability to maintain and extend projects.
  • 35. 15 Chapter 1: Introduction to jQuery Client-side caching can lead to headaches when updates are made to CSS or script files. ❑ ❑ Browsers will continue to use the old version of the CSS and script files after an update is made, when caching is working correctly. The good news is, all of the preceding caveats can be overcome. The bad news is, it’s not particularly easy to overcome them. The best way to implement efficiency in markup, JavaScript, and CSS documents is to make the effi- ciency automatic. That is to say, write server-side applications that handle efficiency tasks for you. A well-designed professional content management system will work out those bits for you. It will allow you to make your JavaScript, markup, and CSS documents modularized, and separate them based on the task each is designed to perform, but automatically combine and compress those documents for you. Unfortunately, not everyone can use a professional content management system to serve their content. For those individuals, there are some compromises to be made: JavaScript and CSS can be hand-compressed using a web-based utility like Dean Edwards’s ❑ ❑ packer, http://dean.edwards.name/packer. Development can continue to be modularized, and the compression and consolidation portion of development simply becomes a manual task. You can limit the amount of white space you use in a document. Indent content with two spaces ❑ ❑ instead of four. Overcoming the headaches with document caching, on the other hand, is a much easier task. You can force a browser to update a document by changing its path. For example, say you have the following script included in your markup: <script src=’/script/my.js’ type=’text/javascript’></script> You change the path from /script/my.js to /script/my.js?lastModified=09/16/07. The latter references the same, my.js, but is technically a different path to the browser and, consequently, will force the browser into refreshing its cached copy of the document. The ?lastModified=09/16/07 portion of the path is what’s called the query string portion of the path. The query string begins with a question mark and then con- tains one or more query string variables. Query string variables are used by a server-side programming language or client-side JavaScript to pass information from one document to another. In this example, there is no information being passed per se. You’re including the time of the last modification, although I could have just as easily included the revision, or even a random string of characters. The inclusion of a query string in this example has only one purpose: to force the browser into refreshing the cached version of the document. The same can be done with CSS: <link type=’text/css’ rel=’stylesheet’ href=’/styles/my.css?lastModified=09/16/07’ /> In the preceding snippet of markup that includes an external CSS document, the query string is used to force a refresh of the browser’s cached copy of the style sheet my.css. In the next section, I talk about some conventions specific to JavaScript.
  • 36. 16 Part I: jQuery API JavaScript Conventions In JavaScript, there are several things that should be considered bad practice and avoided: Include All Script in External Documents ❑ ❑ — JavaScript code should only be included in exter- nal script files. Script should not be embedded in markup documents or be included inline, directly on markup elements. Write Clean, Consistent Code ❑ ❑ — JavaScript code should be neatly formatted and organized in a consistent, predicable way. Namespace JavaScript Code ❑ ❑ — JavaScript variables, functions, objects, and the like should be namespaced to minimize potential namespace conflicts and collisions with other JavaScript applications. Avoid Browser Detection ❑ ❑ — Browser detection should be avoided where possible. Instead, detect specific browser features. In the next sections, I present cursory, generalized overviews of each of the preceding concepts. Include All Script in External Documents Part of making JavaScript non-obtrusive means making JavaScript complementary and supplemental, rather than required and mandatory. This concept is explored in detail throughout this book; however, it should be noted why this is the best approach. Consider the following code example: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”vvvvvv “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”> <head> <meta http-equiv=”Content-Type” content=”application/xhtml+xml; charset=UTF-8”/> <title>Inline JavaScript</title> <link rel=’stylesheet’ type=’text/css’ href=’style.css’ /> </head> <body> <p> <img src=’pumpkin.jpg’ alt=’Pumpkin’ /> <a href=’javascript:void(0);’ onclick=’window.open( “pumpkin.jpg”, “picture”, “scrollbars=no,width=300,height=280,resizable=yes” );’>Open Picture</a> </p> </body> </html> Combine the preceding markup with the following style sheet: img { display: block;
  • 37. 17 Chapter 1: Introduction to jQuery margin: 10px auto; width: 100px; border: 1px solid rgb(128, 128, 128); } body { font: 14px sans-serif; } p { width: 150px; text-align: center; } The preceding code gives you something like what you see in Figure 1-1. In Figure 1-1, you see what is probably a pretty common scenario: You have a thumbnail, and you can click to see a bigger version of the thumbnail. This is the kind of thing that JavaScript works well for — giving you the bigger version in a separate pop-up window that doesn’t have any controls. Now let’s examine why what I did in Figure 1-1 was the wrong way to go about adding this functionality. Here are the problems with this approach: If JavaScript is disabled, viewing the larger picture doesn’t work. ❑ ❑ JavaScript can be disabled out of personal preference. ❑ ❑ JavaScript can be disabled because of company policy. ❑ ❑ JavaScript can be disabled if the end-user is using a handheld device or viewing the site ❑ ❑ through any kind of alternative medium. Search bots may not understand the JavaScript, so Search Engines may not properly index this ❑ ❑ content. Placing the JavaScript directly in the markup document adds unnecessary bloat and complexity ❑ ❑ to the markup document. The overwhelming point in all of this is that inline JavaScript is a really bad way to approach adding complementary, interactive functionality to a web document. Here is a better approach to the application presented in Figure 1-1. First, you take the inline JavaScript out of the markup and replace it with a reference to an externally loaded JavaScript. In the following example, I’ve named the externally loaded JavaScript thumb.js: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”> <head> <meta http-equiv=”Content-Type” content=”application/xhtml+xml; charset=UTF-8”/> <title>Inline JavaScript</title> <link rel=’stylesheet’ type=’text/css’ href=’style.css’ /> <script type=’text/javascript’ src=’thumb.js’></script>
  • 38. 18 Part I: jQuery API </head> <body> <p> <img src=’pumpkin.jpg’ alt=’Pumpkin’ /> <a href=’pumpkin.jpg’>Open Picture</a> </p> </body> </html> Then in the externally loaded JavaScript you do something like the following: window.onload = function() { var $nodes = document.getElementsByTagName(‘a’); for (var $i = 0, $length = $nodes.length; $i < $length; $i++) { $nodes[$i].onclick = function($e) { window.open( this.href, “picture”, “scrollbars=no,width=300,height=280,resizable=yes” ); $e? $e.preventDefault() : (window.event.returnValue = false); }; } }; With the preceding bits of code, you get the same results that you saw in Figure 1-1, and an example of non-obtrusive JavaScript. Non-obtrusive JavaScript provides extended, interactive functionality within a web document, but does not do so in a way that obstructs using the document in a plain-vanilla man- ner. That is to say, with JavaScript disabled, you are still able to use the website and get what you need from it. In the preceding example, the JavaScript is moved to an external document called thumb.js. thumb.js gets all <a> elements present in the document with document.getElementsByTagName(‘a’). Each <a> ele- ment is placed in an array called $nodes, and then a for loop is used to iterate through every <a> element present in the $nodes variable. This is done by making a counter, variable $i; then the number of <a> elements is assigned to a variable called $length via the $nodes.length property. Now the for loop will execute once for every <a> element present, and the variable $i will increment by a count of 1 each time. When the variable $i contains a count that’s more than the number of <a> elements, execution of the for loop will end. Inside the for loop, you have an onclick event that’s assigned to each <a> element present in the $nodes array. An anonymous function is assigned to the onclick event. When a user clicks on an <a> element, the anonymous function will be executed. Within the anonymous function, the <a> element’s proper- ties are available in a special object called this. You see a call to the window.open method; the href prop- erty of the <a> element is passed as the path to open in the new window (this.href), then the window name and some window parameters are defined. So far, the user clicks on an <a> element and gets a pop-up window. You want the window to pop up instead of initiating the default action that occurs when a user clicks on a link (which is for the browser to navigate to the document defined in the href attribute of the <a> element). Stopping the default
  • 39. 19 Chapter 1: Introduction to jQuery action, unfortunately, depends on what browser you’re using. IE has its way, and all the others have a standard way. The JavaScript code accounts for both in the following line: $e? $e.preventDefault() : (window.event.returnValue = false); The preceding line says that if the variable $e evaluates to a Boolean true value, execute the prevent​ Default method of the event object, as in, $e.preventDefault();, otherwise, if $e evaluates to a false value, evaluate this expression: (window.event.returnValue = false). So if $e is true, use the standard W3C method for preventing the default action; if $e is false, use Microsoft’s method for preventing the default action. In this very simple example, you’ve seen how a really simple example can balloon into something much more complex. All of the concepts I’ve presented in this example are ones I continue to revisit through- out this book, but you get a pretty good idea of some of the challenges that non-obtrusive JavaScript prevents. You run into situations in which one browser has one way of doing things, and another has its way of doing things, and sometimes all of the popular browsers differ on how to go about accomplish- ing a given task. Therefore, doing JavaScript the right way often involves quite a bit more thought and planning. The good thing about this additional thought and planning is that it becomes second nature once you understand how to account for all of the browser differences. The good news is that there are people out there looking out for you, and who’ve already braved all the deep, dark corners of browser inconsistencies, incompatibilities, and lack of common, coherent standards. At this point, you might be asking yourself, so what are the benefits of going through all of this hassle to get non-obtrusive, multiplatform JavaScript? I’m glad you asked. In the preceding example, if JavaScript had been disabled, the end-user could still have clicked ❑ ❑ on the link to see a larger version of the thumbnail image. This makes your website much more accessible. When JavaScript is included in an externally loaded file, you get a speed boost, since the ❑ ❑ JavaScript only has to be loaded once, and from there on is cached by the client browser. While it takes some planning, the cross-browser inconsistencies and incompatibilities can be ❑ ❑ completely overcome. You can achieve better search rankings, since search engines can now access and see all of your ❑ ❑ content. You’ll appear more hip, all the girls (or guys) will like you, a pretty butterfly will land on your ❑ ❑ shoulder, there will be world peace, and so on. Well, maybe not that last one, but non-obtrusive JavaScript is, simply, A Good Thing™. Write Clean, Consistent Code It’s important to follow some predetermined criteria for producing clean, consistent, well-organized code. In the professional world, most programmers have a particular way they like to see their code for- matted. Earlier in this section, I talked about how indenting and spacing markup and CSS documents can help you more easily catch errors in those documents and make those documents more maintain- able. Well, the same can be applied to JavaScript, although, with JavaScript and other programming lan- guages, programming conventions are typically much more defined, down to a very fine-grained level of detail. Here I talk about each of the programming conventions that I follow for writing JavaScript source code.
  • 40. 20 Part I: jQuery API Indenting and Line Length It’s a good idea to indent your code so that it’s easier to read and maintain. Take the following, for example: window.onload=function(){var $nodes=document.getElementsByTagName(‘a’); for(var $i=0,$length=$nodes.length;$i<$length;$i++){$nodes[$i].onclick=function($e){ window.open(this.href,”picture”,”scrollbars=no,width=300,height=280,resizable=yes”); $e? $e.preventDefault():(window.event.returnValue=false);};}}; In the preceding block of code, you see the contents of thumb.js presented above in this section, format- ted without any indenting or spacing. Now, imagine that the preceding code is 10,000 lines of code spread out over many files, all formatted the same way. It’s not a bad idea to reduce spacing for a live, production script; in fact, many professionals use compression routines specifically for this. But those same professionals don’t maintain their scripts in the compressed format and often have a rigid pro- gramming standard to which every script they produce must conform. A common, fairly universal programming standard is setting the size of an indentation to four spaces, although some use just two spaces. This is in addition to setting a blanket rule that tabs cannot be used in place of individual spaces, even though, technically, a tab character results in less bytes added to a file when compared to four individual space characters. The “no tab” rule exists because of the wide variance in the interpretation of what a tab character is in text applications. Some text applications say that a tab character is equal to eight individual spaces. Some text applications say that a tab character is equal to four individual spaces, while others still let you explicitly define how big a tab character is. These variances have led to the tab character being unreliable. Most professional integrated developer environments (IDEs) let you define the [Tab] key on a keyboard as individual spaces, in addition to let- ting you define how many spaces to insert. Some examples of IDEs are Adobe Dreamweaver, Zend Studio, and Microsoft Visual Studio: These are all development environments for either directly writing or generating source code. Additionally, most IDEs try to guess what you mean when writing a source document, by intelligently adjusting the num- ber of spaces. For example, when you press [Return] to begin a new line in your source code document, the IDE can indent the new line with at least as much space as the preceding line. Most IDEs behave this way by default. Dreamweaver automatically inserts two spaces when you hit the [Tab] key. Zend Studio can be configured to insert spaces instead of tab characters when you press the [Tab] key. Throughout this book, I try to use four characters for a [Tab] key, although limited space may sometimes require that I use two characters. Generally, the professional standard for client-side source code is two characters, since four characters makes file sizes much larger. I’ve stuck with four because concerns about file size and bandwidth usage can be addressed by compressing your source code when it’s used on a production website. Control Structures Control structures include programming statements that begin with the keywords if, if else, switch, case, else, for, while, try, catch, and the like. Control structure programming statements are the building blocks of any programming language. Let’s see how control structure statements should be formatted with regard to popular programming standards and guidelines.
  • 41. 21 Chapter 1: Introduction to jQuery Although, ultimately, different people have different preferences for how to write source code, there are two prevailing methods for formatting control structures in use by the majority of the professional pro- gramming community. The following convention, which is formally called K&R Style, is included in Sun’s Coding Standards Guidelines for Java: if ($condition) { $something = 1; } else if ($another) { $something = 2; } else { $something = 3; } In the preceding code example, you see that the curly braces and the parentheses are used as markers for indention. Compare the preceding to the next convention, which is known as Allman Style, which is the default in Microsoft Visual Studio: if ($condition) { $something = 1; } else if ($another) { $something = 2; } else { $something = 3; } In Allman Style, all the curly braces line up in the source code, which makes it easier to detect when one is missing, in addition to preventing typos like missing curly braces from occurring in the first place, since you have a visual aid for their placement. When function calls, like window.open in the example, are very long, sometimes the function call is bro- ken up over multiple lines to make it easier to read. To the browser, window.open( this.href, “picture”, “scrollbars=no,width=300,height=280,resizable=yes” ); and window.open(this.href, “picture”, “scrollbars=no,width=300,height=280,resizable=yes”);
  • 42. 22 Part I: jQuery API are exactly the same. The former example just makes it easier for humans to parse the arguments pres- ent in the function call. Sometimes these two conventions are mixed to form a third convention, which is known as the One True Brace convention. This convention is defined in the Coding Standards Guidelines for PHP’s PEAR repository. window.onload = function() { var $nodes = document.getElementsByTagName(‘a’); for (var $i = 0, $length = $nodes.length; $i < $length; $i++) { $nodes[$i].onclick = function($e) { window.open( this.href, “picture”, “scrollbars=no,width=300,height=280,resizable=yes” ); $e? $e.preventDefault() : (window.event.returnValue = false); }; } }; In the One True Brace convention, the function assigned to window.onload follows the Allman Style, while the code within it follows K&R Style. This is the convention that I prefer for writing JavaScript, since it’s more compact and leads to smaller file size, although I prefer the Allman Style for writing non-JavaScript code for its greater readability, since with other languages, file size is less of an issue. Which programming convention you use is a matter of personal taste. Often which convention to use can lead to endless battles among programming teams, since sometimes people have different tastes. You should use whichever convention makes the most sense for you. Although the three I’ve showcased are the most popular, there are a multitude of variations that exist out in the wild. More information about programming indention styles can be found on Wikipedia at http://en.wikipedia.org/wiki/ Indent_style. Optional Curly Braces and Semicolons In the conventions above, you’ll note that there is always a single space between the keyword that begins the control structure, like if, and the opening parenthesis. The following is a switch control structure using the first convention: switch ($variable) { case 1: $condition = ‘this’; break; case 2: $condition = ‘that’; break; default: $condition = ‘those’; }
  • 43. 23 Chapter 1: Introduction to jQuery Note in the preceding that no break statement appears in the default case. As the default, a break is implied, and it is necessary to include the break statement. I tend to deviate from the norm with how I prefer switch control structures to be written. switch ($variable) { case 1: { $condition = ‘this’; break; }; case 2: { $condition = ‘that’; break; }; default: { $condition = ‘those’; }; } I like to add curly braces around each case in the switch statement; I do this because I believe it makes the switch statement easier to read; however, ultimately, these are not necessary. Concerning optional curly braces, I always include them, even if they’re technically optional. The same goes for semicolons. Terminating each line with a semicolon is technically optional in JavaScript, although there are some circumstances in which you won’t be able to omit it. I include all optional semicolons and curly braces, as I think that this not only makes the code cleaner, more organized, and consistent, but also gives you a technical benefit. If you want to compress your code to remove all additional white space, comments, and so on, these optional bits suddenly are no longer optional, but needed to keep the program functional once it’s been compressed. In the following example, you can see what I mean by optional components: if ($condition) $something = 1 else if ($another) $something = 2 else $something = 3 In JavaScript, the preceding code is perfectly valid. The semicolon is implied where there is a line break. And as long as there is only a single statement being executed, technically you don’t have to include curly braces. However, the above fails when it is compressed: if ($condition) $something = 1 else if ($another) $something = 2 else $something = 3 The preceding fails with a syntax error when you try to execute it. It fails because the script interpreter has no idea where you intend one statement to end and the next to begin. The language could probably be extended to guess in some circumstances, but it’s better to just be as explicit as possible. Something else that you might think is odd is the inclusion of a semicolon after some function defini- tions. You’ll see this in JavaScript because a function can be a type of data, just like a number is a type of data or a string is a type of data. In JavaScript, it’s possible to pass a function around as you would a
  • 44. 24 Part I: jQuery API number or a string. You can assign a function to a variable and execute the function later. You’ve already seen an example of this, and here it is again in the following code example: window.onload = function() { var $nodes = document.getElementsByTagName(‘a’); for (var $i = 0, $length = $nodes.length; $i < $length; $i++) { $nodes[$i].onclick = function($e) { window.open( this.href, “picture”, “scrollbars=no,width=300,height=280,resizable=yes” ); $e? $e.preventDefault() : (window.event.returnValue = false); }; } }; In the preceding code example, you can see that a function is being assigned to the onload event of the window object. The function definition is terminated with a semicolon. Again, that semicolon is techni- cally optional in this example, but I include it because I want the code to work if it gets compressed, and I think that it makes the code more consistent, organized, and easier to follow. Naming Variables, Functions, Objects, . . . Variable naming is also accounted for in the coding standards I follow throughout this book. I always use the camelCase convention when naming variables, functions, objects, or anything that I can poten- tially invent a name for. I like to append a dollar sign ($) to local variable names (variables that are exe- cuted within the scope of the currently executing function or object method). I name global variables without a dollar sign to indicate that they are global. The dollar sign is technically optional in JavaScript. You aren’t required to begin variable names with it, but I use it to assist with identifying variable scope. Also, it’s worth noting that my use of the dollar sign originates from my roots as a PHP programmer, where the dollar sign is a required prefix for variable names. Some people find this convention odd, so, again, I implore you to do what makes the most sense to you. Namespace JavaScript Code It’s important to think about the big picture when writing an application. Whether you’re writing an application for your own use or writing an application that will be deployed in varying environments that you have no control over, you’re likely to run into one problem at some point in your career: nam- ing conflicts. I touched on this topic when I talked about namespacing class and ID names in your CSS and markup. The same principles I talked about there are also applicable to JavaScript. Your script appli- cations need to run without invading the global namespace too much. I say “too much,” because you’ll need to invade it somewhat, but you need to do so in a controlled and intelligent way. As you may have done for your markup and CSS, namespacing your JavaScript may be as simple as sticking to object- oriented code, wrapping all of your programs in just one, or a handful of objects and then naming those objects in the global namespace in a non-invasive way. A common approach is to namespace those objects with a prefix of some kind that doesn’t infringe on some other existing project. One example is how the jQuery JavaScript framework is namespaced. jQuery does a lot, but for all of the code that’s included in jQuery, there are precious few intrusions made on the global namespace, the “jQuery” object, and the
  • 45. 25 Chapter 1: Introduction to jQuery dollar sign method the jQuery object is aliased to. All of the functionality that jQuery provides is pro- vided through those objects. Without a well-thought-out approach to the namespacing problem, it’s possible that your application may cause conflicts with others. It’s best to just assume that everything you place in the global namespace will cause a conflict, and thus set out to make as minimal as possible an intrusion into the global namespace. Avoid Browser Detection Browser detection can be a real annoyance. You’re surfing the Web using your favorite browser, and you hit a website that locks you out — not because your web browser is technically incapable, but because it didn’t match what the website’s creators presupposed would be capable. So, I propose the following: Make no assumptions about the capabilities of a visitor’s browser. ❑ ❑ Test for feature compatibility, rather than a browser name or browser version. ❑ ❑ Account for the official standards and the de facto standards. (Official standards should take ❑ ❑ precedence — de facto standards will either become or be replaced by the former.) The world is always changing — what’s most popular today may not remain the most popular ❑ ❑ in the months and years to come. It may be time to turn to a framework for some compatibility bridging. ❑ ❑ Anyone remember a little company called Netscape? At one time, Netscape was the dominant, de facto standard. Now Netscape holds just under 0.6 percent of world market share, and Microsoft’s IE is domi- nant. At its most popular, IE held more than 90 percent of the market. Now IE holds around 70 percent; Firefox holds 21 percent; and Safari holds roughly 7 percent, Opera and others have around 2 percent combined. The browsing market can and does fluctuate. In the real world, there are lots of people who use less popular browsers. And 2 percent may sound small at first glance, but keep in mind that is 2 percent of a very large number. According to www.internetworldstats.com, in 2008, as I write this, there are just over 1.4 billion Internet users world-wide, which is 21.9 percent of the world’s population. Therefore, the so-called less popular browsers aren’t really doing too shabby in the grand scheme of things, and while 2 percent sounds small, it’s actually a pretty large base of users. Summary jQuery takes what would otherwise be a more complex or verbose task in plain-vanilla JavaScript, and it makes it much easier, sometimes reducing many lines to one or a few. Throughout this book, you will learn about what jQuery has to offer and how to use its simple, easy-to-understand API to write spectacu- lar, professional-appearing web applications that have all the polish and sparkle of a Fortune 500 company. In this chapter, I talked a little about what jQuery is, where it comes from, and who develops and main- tains it; and I showed you how to install it and begin using it. In the next chapter, you get right down to business, learning about jQuery’s powerful implementation of the Selectors API and its world-class Event API. If you are interested in learning more about jQuery’s origins, visit www.jquery.com and www.ejohn.org.
  • 46. 26 Part I: jQuery API This chapter also covered some things that a good programmer will want to get into the habit of doing, such as adopting a formal programming convention and avoiding conflicts with others’ code through using a namespace of some sort (whether that be via a feature provided by the language, or through prefixing the names that you use that make an impact on the global namespace). I’ve shown a few of the practices that I have adopted for myself, although I should emphasize that it doesn’t matter what pro- gramming convention that you adopt, but rather that you adopt one. The premise of a programming convention is that you have a set of rules that you can follow to format your code so that it is neat, orga- nized, and easy to follow. My conventions might not be what you want, but there are many others to choose from. You should avoid detecting the user’s browser, especially when it may lead to one group or another being locked out from functionality. Your code should take advantage of client-side caching and the increase in performance it provides. In my opinion, it is better to write code in neatly organized modules and combine those into a larger script later using server-side programming. Finally, it is also important that you adopt standards for the presentation and maintenance of client-side markup and CSS. Choose either XHTML or HTML, since both are accepted standards. I personally use XHTML, although XHTML may be too strict for your taste. Use the W3C’s validation services to discover errors in your markup or your CSS, as sometimes errors in CSS or markup can cause errors in your JavaScript.
  • 47. 2 Selecting and Filtering In this chapter, I talk about jQuery’s sophisticated implementation of a Selectors API, which pro- vides the ability to select elements in the DOM using selectors just like you use in CSS. jQuery’s Selectors API allows you to select one or more elements from the DOM using a selector, then you can either use that result set, or you can pass those elements on to be filtered down to a more spe- cific result set. If you’ve never heard of a selector before, then I recommend that you have a look at my book, Beginning CSS: Cascading Style Sheets for Web Design, 2nd ed. (Wrox, 2004; ISBN 978-0-7645-7642-3), which has extensive coverage of selectors. In CSS, you can apply style to one or more elements by writing a style sheet. You choose which elements to style based on the syntax that appears in the first part of a CSS rule, before the first curly brace, which is known as the selector. Here is a sample CSS selector: body form#hProductSummaryDialogue { display: block; position: absolute; z-index: 1; top: 22px; left: 301px; right: 0; bottom: 24px; width: auto; margin: 0; border: none; border-bottom: 1px solid rgb(180, 180, 180); } Using markup and CSS, you are able to assign IDs and class names to elements, and you are able to control the presentational aspects of elements very specifically using selectors. In jQuery, that concept of selectors as applied to CSS is also applied to the concept of the DOM, or Document Object Model. In the DOM, you have available to you every element that exists in the markup of your document, and you are able to travel the DOM and select the elements you want to work with using selectors, just like you use in your CSS style sheets.
  • 48. 28 Part I: jQuery API Once you’ve selected elements from the DOM, you can apply behavior to them. You can make some- thing happen when a user clicks on an element, for example. You can make something happen when the user’s mouse cursor comes over or leaves an element. Basically, you can make your web documents look and behave more like desktop applications. You are no longer limited to static content as you are with markup and CSS alone — you can apply behavior as well. In this chapter, I describe how to use jQuery’s Selectors API to retrieve elements from a document, in addition to providing some practical examples of usage. I also describe how you can chain calls in jQuery. One use for this is filtering elements, which you would do to reduce a larger selection of elements down to a smaller selection. Finally, I discuss how jQuery’s Event API works in relation to the W3C’s Event API and Microsoft’s. The Origin of the Selectors API The concept of a Selectors API was first dreamed up by Dean Edwards, a JavaScript guru, who first cre- ated a Selectors API in JavaScript in a free, Open Source package he called cssQuery. Not long after Dean pioneered the idea and produced a working, proof-of-concept implementation of that idea, it was taken up and expanded upon by John Resig (and other JavaScript framework authors, mutually exclusive to John’s efforts) and implemented in his jQuery framework. This led to some back-and-forth collaboration and competition between Dean, John, and other JavaScript framework authors, which resulted in much needed performance boosts in these ad hoc implementations, which at their conception were quite slow in some scenarios. Not long after Dean came up with the concept of a Selectors API, W3C members and editors Anne van Kesteren and Lachlan Hunt drafted it into a specification for the W3C. The official W3C Selectors API involves two methods, one for selecting a single element called document.querySelector() and one for selecting multiple elements called document.querySelectorAll(). The names for the official API were under considerable debate for quite some time, as no browser makers could agree on the names used. The names were finally put to a vote, with these names being the ones decided on. The controversy surrounding the names was not without merit, as this API is quite possibly the most important change to JavaScript that will have a lasting impact for years to come. It’s important in that, in one fell swoop, it replaces methods like document.getElementById, document.all, and document.getElementsByTagName, which are no longer really needed — since these methods let you use selector syntax, you can select by ID, by tag name, by class name, or by context, via whatever selectors the browser already supports for CSS. As I write this, the W3C version is a Candidate Recommendation, and document.querySelector and document.querySelectorAll are implemented natively in Internet Explorer 8, Safari 3, Firefox 3.1, and Opera 10. For once, a new feature is present and accounted for in the latest releases of all of the major browsers! The great thing about jQuery and other JavaScript frameworks is that they had their own versions of the Selectors API already implemented prior to its native inclusion in browsers, which allows them to use the native implementation, if it is available. Using the native implementation makes selecting ele- ments screamingly fast. Otherwise, if the user has an older browser, the framework can fall back on its own, slower, JavaScript-based implementation. This means that when using a JavaScript framework like jQuery, the Selectors API is ubiquitously available across all platforms it supports. jQuery is officially compatible with IE 6+, Firefox 1.5+, Safari 2.0.2+, and Opera 9+.
  • 49. 29 Chapter 2: Selecting and Filtering Using the Selectors API Using the Selectors API in jQuery is very easy. First, you must know that everything you want to do with jQuery originates from a single, very simply named object that is called $. That’s right, its name is a single dollar sign. As I mentioned back in Chapter 1, you can also use “jQuery” in place of the dollar sign, but from here on throughout this book, I will use only the dollar sign, and I will refer to it either as “the dollar sign object” or “the dollar sign method,” depending on context, because it is really both a method and an object at the same time. The dollar sign is both a method and an object because it can be used like a function call, but it also has member properties and methods that you can call. The dollar sign is named after a single dollar sign for one reason only, and that is to reduce the amount of code that you have to write. This is why a dollar sign is used instead of, say, document.getElementsBySelector(), which is very long, verbose, and annoying to type out. Here’s a very simple example of how you would use this method with a selector to add a click behavior to a collection of links. Basically, the object of the following code is to force the links to open in a new window, instead of using the “target” attribute, which does not validate under XHTML Strict. Let’s say that you have a markup document that looks like this: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> <html xmlns=’http://www.w3.org/1999/xhtml’ xml:lang=’en’> <head> <meta http-equiv=’content-type’ content=’text/html; charset=utf-8’ /> <meta http-equiv=’content-language’ content=’en-us’ /> <title>Link</title> <script type=’text/javascript’ src=’../../../Source Code/jQuery/jQuery.js’> </script> <script type=’text/javascript’ src=’Figure 2-1.js’></script> <link type=’text/css’ href=’Figure 2-1.css’ rel=’stylesheet’ /> </head> <body> <ul id=’tmpFavorites’> <li><a href=’http://www.wrox.com’>Wrox</a></li> <li><a href=’http://www.gizmodo.com’>Gizmodo</a></li> <li><a href=’http://www.apple.com’>Apple</a></li> <li><a href=’http://www.jquery.com’>jQuery</a></li> </ul> </body> </html> In the preceding markup document, you have a simple unordered list that contains four links. You take that markup and put it with the following CSS: body { font: 16px sans-serif; } ul { list-stlye: none;
  • 50. 30 Part I: jQuery API margin: 0; padding: 0; } a { text-decoration: none; } The preceding CSS document does little more than make that list look a little prettier — it neither really adds to nor takes away from the example. Finally, you add the following JavaScript document to the markup: var tmpExample = { ready : function() { // Get all links… $(‘ul#tmpFavorites li a’).click( function($e) { $e.preventDefault(); window.open(this.href, ‘FavoriteLink’, ‘’); } ); } }; $(document).ready(tmpExample.ready); The preceding code, all put together, should look something like what you see in Figure 2-1. Figure 2-1 When you click on a link in the example, you should see the link open in a new window or tab, depend- ing on how you have your browser’s preferences set up to handle pop-up windows. In the preceding example, you’re using JavaScript to force the links in the <ul> element with ID name tmpFavorites to open in a new window or tab. To do this, in the JavaScript, you created a JavaScript Object Literal, which isn’t the only way to create a new object — there are lots of ways to do this, but I just happen to like this one. The new object is called tmpExample, and it has one member method, called ready; then inside the ready method are all the things you want to do when the document is ready.
  • 51. Another Random Scribd Document with Unrelated Content
  • 52. TESSELLATED PAVEMENT From Lysons’ Account of the Roman Villa discovered at Woodchester. The character of the Roman remains dug up from time to time within these walls shows that it was formerly a place of great resort. Under the protection of this citadel, and later under the protection of the Pax Romana, villas were built up outside the walls for the residence of the better sort. All round the walls also sepulchral remains have been discovered; they were afterwards included in the larger wall of the city which was built towards the close of the fourth century. London was then, and for many years afterwards, divided into London east and west of the Walbrook. On the western side was the quarter of the poorer sort; they had cottages on the foreshore—as yet there was no wall. The better class lived outside the fort, along the eastern side of Walbrook, and in Cornhill, Threadneedle Street, and Bishopsgate Street. Down below were the three Roman ports, afterwards called Billingsgate, Dowgate, and Queenhithe. Walking down Thames Street one finds here and there an old dock which looks as if it had been there from time immemorial. I have sometimes been tempted, when in Thames Street—that treasure-house of memories, survivals, and suggestions—to think that these narrow lanes sloping to the river are of Roman origin, left when all the rest was wrecked and lost, and that they are still of the
  • 53. same breadth as they were in the fourth century. This, however, is not the case. I shall show presently the origin and meaning of these narrow streets running up the hill from the river into Thames Street: they are all, in fact, connections of the quays on the foreshore with the merchants’ warehouses in Thames Street. Along the better streets, on the north of Thames Street, the traders put up their stalls and kept their shops; the stalls were at first mere temporary sheds resting against the walls of villas. These villas belonged, not to the millionaire Lucullus, for whose palace the whole world could be ransacked, but to the well-to-do merchant, whose taste was not much cultivated. He called in the best artist of the city. “Build me a villa,” he said, “as good as my neighbour’s. Let there be a fine mosaic pavement; let there be fountains; let there be paintings on the walls, lovely paintings—nymphs and fauns, nymphs bathing, plenty of nymphs, dancing girls, plenty of dancing girls; paint me Hercules drunk, Loves flying and playing tricks, warriors with shields, sea pieces, ships; paint me my own ships sailing. And take care of the hypocaust and the warming pipes, and see that the kitchen is suitably furnished.” The earliest, the natural port of London was the mouth of the Walbrook, called afterwards Dowgate. In the western wall of the Roman citadel was the gate which served at once for the road or street across the City to Newgate, and for that part of the trade which belonged to the citadel. The Walbrook at this time was a considerable stream. It was partly a tidal stream, but it was fed from above by many tributaries on the moorland. Here the ships first began to load and to unload. For their convenience quays were constructed on piles driven into the mud and shingle of the foreshore. As the trade increased, the piles were pushed out farther and the quays were broadened. When trade increased and the difficulties of getting through the bridge were felt, another port was necessary. It was perfectly easy to construct one by cutting it out of the soft foreshore and then banking it up with strong piles of timber. Piles and beams were also
  • 54. driven in on either side for the support of quays, which could thus be extended indefinitely. The place chosen was what is now called Billingsgate. It was close to the bridge and the bridge gate; so that while goods could be landed here for the trade of the City—whence they could be easily distributed throughout the north and midland of the island,—communication was established with the south by means of the bridge (see Appendices I. and II.). Later on, but one knows not when, the port of Queen Hythe, formerly Edred’s Hythe, was similarly constructed. I am inclined to believe also that Puddle Dock represents another ancient port; but whether Roman or Saxon, it is now impossible to decide. The poorer part of the City was that part lying between Puddle Dock and Dowgate: we do not find tessellated pavements here, nor remains of great buildings. The houses which stood upon the pavements were modest compared with the villas of the Roman millionaire; but they were splendid compared with other houses of the City. For the convenience of the better sort there was the bath, in which everybody spent a part of the day; for the merchants there were the quays; there was the theatre; and there was the amphitheatre. It is true that no trace has ever been found of theatre or of amphitheatre; but it is also true that until recently no trace was found of the Roman citadel, and, as I have said, no trace has ever been found of forum or of temples. We will return to this subject later. To one standing at the south end of the narrow wooden bridge across the Thames, Augusta, even before the building of the wall, appears a busy and important place. Exactly opposite the bridge, on a low eminence, was a wall, strong though low, and provided with rounded bastions. Above the wall were seen the columns of the forum and of two temples, the roofs of the great hall of justice and of the official offices and residences.
  • 55. Along the quays were moored the ships. On the quay stood sheds for warehouses in a line. Behind these warehouses were barracoons for the reception of the slaves waiting to be transported to some other part of the Empire, there to await what Fortune had in store for them—perhaps death in a gladiatorial fight, perhaps service on a farm, perhaps the greatest gifts of Fortune, viz. a place in a Roman cohort, opportunities for showing valour and ability, an officer’s commission, the command of a company, then of a legion, then of a victorious army; finally, perhaps the Purple itself and absolute rule over all the civilised world. The streets behind the warehouses were narrow and steep, the houses in them were mean. Everywhere within the area afterwards enclosed by the wall were villas, some small, some large and stately. It was a noisy city, always a noisy city —nothing can be done with ships without making a noise. The sailors and the stevedores and the porters sang in chorus as they worked; the carts rolled slowly and noisily along the few streets broad enough to let them pass; mules in single file carried bales in and out of the city; slaves marched in bound and fettered; in the smaller houses or in workshops every kind of trade was carried on noisily. Smoke, but not coal smoke, hung over all like a canopy. In such a restoration of a Roman provincial town one seems to restore so much, yet to leave so much more. Religion, education, literature, the standard of necessities and of luxury, the daily food, the ideas of the better classes, the extent, methods, and nature of their trade, the language, the foreign element—none of these things can be really restored. Under the protection of the citadel the merchants conducted their business; under its protection the ships lay moored in the river; the bales lay on the quays; and the houses of the people, planted at first along the banks of the Walbrook, stretched out northwards towards the moor, and westwards as far as the river Fleet. It is strange that nothing should be said anywhere about so strong and important a place as the citadel. When was it built, and by whom? When was it destroyed, and by whom? Were the walls
  • 56. standing when the Saxons began their occupation? It appears not, because, had there been anything left, any remains or buildings standing, any tradition of a fortress even, it would have been carried on. The citadel disappeared and was forgotten until its foundations were found in our time. How did this happen? Its disappearance can be explained, according to my theory, by the history of the wall (see p. 112): all the stones above ground, whether of citadel, temple, church, or cemetery, were seized upon to build the wall. Across the river stood the suburb we now call Southwark, a double line of villas beside a causeway. It has been suggested that Southwark was older than London, and that it was once walled in. The only reasons for this theory are: that Ptolemy places London in Kent—in which he was clearly wrong; that the name of Walworth might indicate a city wall; that remains of villas have been found in Southwark; and that a Roman cemetery has been found in the Old Kent Road. But the remains of houses have only been found beside the high road leading from the bridge. They were built on piles driven into the marsh. Up till quite recent times the whole south of London remained a marsh with buildings here and there; they were erected on a bank or river wall, on the Isle of Bermond, on the Isle of Peter, beside the high road. And there has never been found any trace of a wall round Southwark, which was in Roman times, and has always been, the inferior suburb—outside the place of business and the centre of society. Every town on a river has an inferior suburb on the other side—London, Paris, Liverpool, Tours, Florence: all busy towns have inferior transpontine suburbs. Southwark was always a marsh. When the river-bank was constructed the marsh became a spongy field covered with ponds and ditches; when the causeway and bridge were built, people came over and put up villas for residence. In the Middle Ages there were many great houses here, and the place was by some esteemed for its quiet compared with the noise of London, but Southwark was never London. Besides the bridge, there was a ferry—perhaps two ferries. The name of St. Mary Overies preserves the tradition. There are two very
  • 57. ancient docks, one beside the site of the House of St. Mary Overies, and one opposite, near Walbrook. In these two docks I am pleased to imagine that we see the ancient docks of London ferry to which belongs the legend of the foundation of the House. Let us return to the question of amphitheatre and theatre. There must have been both. It is quite certain that wherever a Roman town grew up an amphitheatre grew up with it. The amphitheatre was as necessary to a Roman town as the daily paper is to an American town. It has been suggested that there was no amphitheatre, because the city was Christian. There may have been Christians in the city from the second century; everything points to the fact that there were. It is impossible, however, to find the slightest trace of Christian influence on the history of the city down to the fourth century. W. J. Loftie thinks that the dedication of the churches in the lower and poorer parts of the town—viz. to SS. Peter, Michael, James, and All Saints—shows that there were Christian churches on those sites at a very early period. This may be true, but it is pure conjecture. It is absurd to suppose that a city, certainly of much greater importance than Nîmes or Arles—where were both theatre and amphitheatre,—and of far greater importance than Richborough —where there was one,—should have no trace of either. Since Bordeaux, Marseilles, Alexandria, and other cities of the Roman Empire were not Christian in the second and third centuries, why should London be? Or if there were Christians here in quite early times, theirs was not the dominant religion, as is clearly shown by the Roman remains. There must have been an amphitheatre—where was it? To begin with, it was outside the City. Gladiators and slaves reserved for mock battles which were to them as real as death could make them, wild beasts, the company of ribalds who gathered about and around the amphitheatre, would not be permitted within the City. Where, then, was the amphitheatre of London? At first one turns to the north, with its gardens and villas and sparse population. The existence of the villas will not allow us to
  • 58. place the amphitheatre anywhere in the north near the Walbrook. When the modern traveller in London stands in the churchyard of St. Giles’s, Cripplegate, he looks upon a bastion of the Roman wall where the wall itself took a sudden bend to the south. It ran south till it came to a point in a line with the south side of St. Botolph’s Churchyard (the “Postmen’s Park”), where it again turned west as far as Newgate. It thus formed nearly a right angle—Why? There is nothing in the lie of the ground to account for this deviation. No such angle is found in the eastern part of the wall. There must have been some good reason for this regular feature in the wall. Was the ground marshy? Not more so than the moorland through which the rest of the wall was driven. Can any reason be assigned or conjectured? I venture to suggest, as a thing which seems to account for the change in the direction of the wall, that this angle contained the amphitheatre, the theatre, and all the buildings and places, such as the barracks, the prisons, the dens and cages, and the storehouse, required for the gladiatorial shows. I think that those who built the wall, as I shall presently show, were Christians; that they were also, as we know from Gildas, superstitious; that they regarded the amphitheatre, and all that belonged to it, as accursed; and that they would not allow the ill-omened place of blood and slaughter and execution to be admitted within the walls. It may be that a tradition of infamy clung to the place after the Roman occupation: this tradition justifies and explains the allocation to the Jews of the site as their cemetery. The disappearance of the amphitheatre can be fully explained by the seizure of the stones in order to build the wall. Mr. C. Roach Smith, however, has proposed another site for the theatre, for which he tenders reasons which appear to me not, certainly, to prove his theory, but to make it very possible and even probable. Many Roman theatres in France and elsewhere are built into a hill, as the rising ground afforded a foundation for the seats. That of Treves, for instance, will occur to every one who has visited that place. Mr. Roach Smith observed a precipitous descent from
  • 59. Green Arbour Court into Seacoal Lane—a descent difficult to account for, save by the theory that it was constructed artificially. This indeed must have been the case, because there was nothing in the shape of a cliff along the banks of the Fleet River. Then why was the bank cut away? Observe that the site of the Fleet Prison was not on a slope at all, but on a large level space. We have therefore to account for a large level space backed by an artificial cliff. Is it not extremely probable that this points out the site of the Roman theatre, the seats of which were placed upon the artificial slope which still remains in Green Arbour Court? Mr. Roach Smith read a paper (Jan. 1886) placing this discovery— it is nothing less—on record before the London and Middlesex Archæological Association. The remarkable thing is that no one seems to have taken the least notice of it. Assuming that he has proved his case, I do not believe that he is right as to the houses being built upon the foundations of the theatre, for the simple reason that, as I read the history of the wall in the stones, every available stone in London and around it was wanted for the building of the wall. It was built in haste: it was built with stones from the cemeteries, from the temples, from the churches, from the old fortress, and from the theatre and the amphitheatre outside the wall. As regards the latter, my own view remains unaltered; I still think that the angle in the wall was caused by the desire to keep outside the amphitheatre with all its memories of rascality and brutality. Treves (Colonia Augusta Treverorum) and Roman London have many points in common, as may be apprehended most readily from the accompanying comparison in which Roman Treves and Roman London are placed side by side. We may compare the first citadel of London on the right bank of the Walbrook with Treves; or we may compare the later London of the latter part of the fourth century, the wall of which was built about a.d. 360-390, with Treves.
  • 60. 1. The citadel of London had its western side protected by a valley and a stream whose mouth formed a natural port. The valley was about 140 feet across; the stream was tidal up to the rising ground, with banks of mud as far, at least, as the north wall of the citadel. On the south was a broad river spanned by a bridge. There were three gates: that of the north, that of the west, and that of the bridge on the south. Within the citadel were the official buildings, barracks, residences, and offices. Two main streets crossed at right angles. About half a mile to the north-west (according to my theory) was the amphitheatre. On the north and east was an open moor. On the south a marsh, with rising ground beyond. By the river-side, near the bridge, were the baths. 2. Colonia Augusta Treverorum.—These details are almost exactly reproduced in Treves. We have a broad river in front. On one side a stream which perhaps branched off into two. The gate which remains (the Porta Nigra) shows the direction of the wall on the north from the river. A long boulevard, called at present the Ost Allee, marks the line of the eastern wall, which, like that of London, occupied the site of the Roman wall. A bend at right angles at the end of this boulevard includes the Palace and other buildings. It therefore represents the site of the ancient wall or that of a mediæval wall. It is quite possible that the mediæval wall of the city included a smaller area than the Roman wall, and that the two round towers, here standing in position with part of the wall, represent the mediæval wall. It is also possible, and even probable, that they stand on the site of the Roman wall, which just below the second, or at the second, bent round again to the south as far as the stream called the Altbach, and so to the west as far as the river. That this, and not the continuation of the line of towers, was the course of the Roman wall, is shown by the fact that the baths, the remains of which stand beside the bridge, must have been within, and not outside, the wall. The river wall, just like that of London, ran along the bank to the bridge, and was stopped by the outfall of a small stream. The ground behind the river wall gradually rose. On the other side was a low-lying marsh, beyond which were lofty hills—not
  • 61. gradually rising hills as on the Surrey side of the Thames. The city was crossed by two main arteries, which may still be traced. An extensive system of baths was placed near the bridge on the east side. Within the wall were the Palace of the Governor or of the Emperor, and a great building now called the Basilica; and between them, the remains now entirely cleared away for the exercise ground, once the garden of the barracks. There were three gates, perhaps four. One of them, a most noble monument, still survives. A Roman cemetery has been found beyond the Altbach in the south, and another in the north, outside the Porta Nigra. 3. The comparison of Roman Treves with the later Roman London is most curious, and brings out very unexpectedly the fact that in many respects the latter was an enlargement of the citadel. We know that the wall was constructed hastily, and that all the stonework in the City was used in making it. Like the citadel, however, and like Treves, it had a stream on one side, baths and a bridge and a port within the walls; while the official buildings, as at Treves, were all collected together in one spot. We also find the curious angle, which at Treves may be accounted for by an enlargement of the wall, and at London by the custom of keeping the amphitheatre outside the City as a place foul with associations of battle, murder, massacre, and the ribald company of gladiators, retiarii, prisoners waiting the time of combat and of death, wild beasts and their keepers, and the rabble rout which belonged to this savage and reckless company. That part of London lying to the west of Walbrook was crowded with the houses of the lower classes, and with the warehouses and stores of the merchants. These extended, as they do to this day, all the way from the Tower to Blackfriars. On the rising ground above were the villas of the better class, some of them luxurious, ample, decorated with the highest art, and provided with large gardens.
  • 62. These villas extended northwards along the banks of the little Walbrook. They are also found on the south side in Southwark, and on the west side on Holborn Hill. The principal street of Augusta was that afterwards called Watling Street, which, diverted from the old Watling Street where Marble Arch now stands, carried all the trade of the country through London by way of Newgate, over the present site of St. Paul’s, and so through the citadel, to the market-place and to the port. Another street led out by way of Bishopsgate to the north; and a third, the Vicinal Way, to the eastern counties. The bridge led to a road running south to Dover. There was also a long street, with probably many side streets out of it, as there are at this day, along the Thames. The things which remain of Roman London and may be seen in our museums are meagre, but they yield a good deal of information as to the condition and the civilisation of the City. The foundation of large villas, the rich mosaics and pavements, the remains of statues, the capitals of pillars, the coins, and the foundations of massive walls, clearly indicate the existence of much wealth and considerable comfort. The smaller things in the glass cases, the keys, the hairpins, the glass bottles, the statuettes, the bells, the tools, the steelyards, the mirrors, all point to a civilisation closely imitating that of the capital itself. It is not to a native of London that we must turn for the life of the better class in a provincial city of the fourth century, but to a native of Gaul. Ausonius is a writer whose works reveal the daily life of a great city in Gaul. He was born of good family on both sides. His father was a physician; his grandfather a so-called “Mathematician,” in reality one who still practised the forbidden mystery of astrology. Ausonius himself was educated at Toulouse, and he opened a school of rhetoric at Bordeaux. The rhetoricians not only taught, but also practised, the art of oratory. Whether all rhetoricians were also poets is uncertain: the mere making of verse is no more difficult to acquire than the composition of oratory. There were two classes of teachers: the grammarian, of whom there were subdivisions—the Latin
  • 63. ROMAN SANDALS TAKEN FROM THE BED OF THE THAMES Roach Smith’s Catalogue of London Antiquities. grammarian, skilled in Latin antiquities, and the Greek grammarian, who had studied Greek antiquities; and, above the grammarian, the rhetorician. In every important town over the whole Empire were found the rhetorician and the grammarian; they exchanged letters, verses, compliments, and presents. In a time of universal decay, when no one had anything new to say, when there was nothing to stimulate or inspire nobler things, the language of compliment, the language of exaggeration, and the language of conceit filled all compositions. At such a time the orator is held in greater respect even than the soldier. In the latter the townsman saw the preserver of order, the guardian of the frontier, the slayer of the barbarians who were always pressing into the Empire. He himself carried no arms: he represented learning, law, literature, and medicine. Ausonius himself, in being elevated to the rank of consul, betrays this feeling. He compares himself with the consuls of old: he is superior, it is evident, to them all, save in one respect, the warlike qualities. These virtues existed no longer: the citizen was a man of peace; the soldier was a policeman. If this was true of Bordeaux, then far from the seat of any war, it was much more true in London, which every day saw the arrival and the dispatch of slaves captured in some new border fray, while the people themselves never heard the clash of weapons or faced the invader with a sword.
  • 64. Another profession held greatly in honour was that of the lawyer. The young lawyer had a five years’ course of study. There were schools of law in various parts of the Empire which attracted students from all quarters, just as in later times the universities attracted young men from every country. From these lawyers were chosen the magistrates. Medicine was also held greatly in honour; it was carefully taught, especially in southern Gaul. THE LACONICUM, OR SWEATING BATH From Lysons’ Account of the Roman Villa at Woodchester.
  • 65. The learned class was a separate caste: with merchants and soldiers, the lawyers, orators, grammarians, and physicians had nothing to do. They kept up among themselves a great deal of the old pagan forms. If they could no longer worship Venus, they could write verses in the old pagan style about her. Probably a great many continued, if only from habit, the pagan customs and the pagan manner of thought. The Church had not yet given to the world a crowd of saints to take the place of the gods, goddesses, nymphs, satyrs, and sprites which watched over everything, from the Roman Empire itself down to a plain citizen’s garden. The theatre was entirely given over to mimes and pantomimes: comedy and tragedy were dead. The pieces performed in dumb show were scenes from classical mythology. They were presented with a great deal of dancing. Everybody danced. Daphne danced while she fled; and Niobe, dancing, dissolved into tears. The circus had its races; the amphitheatre its mimic contests and its gladiatorial displays. These things were done at Bordeaux; it is therefore pretty certain that they were also done in London, whose civilisation was equally Gallo-Roman. London was a place of importance equal with Bordeaux; a place with a greater trade; the seat of a Vicarius Spectabilis, a Right Honourable Lieutenant-Governor; one of the thirteen capitals of the thirteen Dioceses of the Roman Empire.
  • 66. TESSELLATED PAVEMENT From Lysons’ Account of the Roman Villa at Woodchester. Any account of Roman London must include a description and plan of a Roman villa. The one I have chosen is the palatial villa which was recovered by Samuel Lysons exactly a hundred years ago at Woodchester. The plan is given in his book, An Account of Roman Antiquities discovered at Woodchester; it shows the arrangement of the rooms and the courts. “The visitor approaching this villa when it was standing observed before him a long low wall with an entrance arch. The wall was probably intended as some kind of fortification; the people in the house numbered enough to defend it against any wandering company of marauders. Within the entrance, where he was received by a porter or guard, the visitor found himself in a large square court, the sides of which were 150 feet. On either side, to east and west, were buildings entered from the great court: in one there were
  • 67. twelve rooms; in the other a curious arrangement of rooms communicating with each other which were thought to be the baths. The rooms on the west side were perhaps the chambers and workshops of the slaves and servants. On the north side a smaller gateway gave access to a court not so large as the first, but still a good-sized court, 90 feet square; it was surrounded on three sides by a gallery, which was closed in winter, as the hypocaust under it indicates. From this court access was obtained to a lovely hall, decorated with a mosaic pavement of great artistic value, with sculptures, paintings, vases, and glass. On either side of this hall were chambers, also decorated in the same way. Under the floors of the chambers was the hypocaust, where were kindled the fires whose hot air passed through pipes warming all the chambers. Fragments of statues, of which one was of Magnentius the usurper, also glass, pottery, marble, horns, coins. The building covered an area of 550 feet by 300 feet, and it is by no means certain that the whole of it has been uncovered. It is interesting to note that on one of the mosaics found at this place is the injunction ‘... B][N][C ...’18—that is, Bonum Eventum Bene Colite—Do not forget to worship Good Luck. To this god, who should surely be worshipped by all the world, there was a temple in Rome. The Roman Briton, if he lived in such state as this, was fortunate above his fellows. But in the smaller villas the same plan of an open court, square, and built upon one, two, or more sides, prevailed. The walls were made of stone up to a certain height, when wood took the place of stone; the uprights were placed near together, and the interstices made air-tight and water-tight with clay and straw; the roof was of shingles or stone tiles. Wall paintings have been found everywhere, as we have already seen; the pavements were in many cases most elaborate mosaics.” The construction of a villa for a wealthy Roman Briton is easy to be understood. As to the question of the smaller houses, it is not so
  • 68. easy to answer. A small house, detached, has been found at Lympne. It was about 50 feet long and 30 feet broad. The plan shows that it was divided into four chambers, one of which had a circular apse. The rooms were all about the same size, namely, above 22 feet by 14 feet. A row of still smaller houses has been found at Aldborough. Almost all the streets in London stand upon masses of buried Roman houses. If we wish to reconstruct the city, we must consider not only the villas in the more open spaces as the official residences in the citadel, but also the streets and alleys of the poorer sort. Now at Pompeii the streets are narrow; they are arranged irregularly; there are only one or two in which any kind of carriage could pass. The same thing has been observed at Cilirnum (Chesters), in Northumberland, and at Maryport in Cumberland. Very likely the narrow streets leading north of Thames Street are on the same sites as the ancient Roman streets of London in its poorer and more crowded parts. It stands to reason that the houses of the working people and the slaves could not be built of stone. The nature of the trade of London is arrived at by considering—(1) What people wanted; (2) what they made, produced, and grew for their own use; and (3) what they exported. ROMAN ROADS RADIATING FROM LONDON
  • 69. To take the third point first. Britain was a country already rich. The south part of the island, which is all that has to be considered, produced iron, tin, lead, and copper; coal was dug up and used for fuel when it was near the surface; skins were exported; and the continual fighting on the march produced a never-failing supply of slaves for the gladiatorial contests. Wheat and grain of all kinds were also largely grown and exported. As for manufactures, pottery was made in great quantities, but not of the finer kinds. Glass was made. The art of weaving was understood. The arts of painting, mosaic work, and building had arrived at some excellence. There were workmen in gold and other metals. As for what people wanted. Those who were poor among them wanted nothing but what the country gave them; for instance, the river was teeming with fish of all kinds, and the vast marshes stretching out to the mouth of the Thames were the homes of innumerable birds. No one need starve who could fish in the river or trap birds in the marsh. In this respect they were like the common sort, who lived entirely on the produce of their own lands and their own handiwork till tea, tobacco, and sugar became articles of daily use. The better class, however, demanded more than this. They wanted wine, to begin with; this was their chief want. They wanted, besides, silks for hangings and for dress, fine stuffs, statues, lamps, mirrors, furniture, costly arms, books, parchment, musical instruments, spices, oil, perfumes, gems, fine pottery. The merchants of London received all these things, sent back the ships laden with the produce of the country, and dispatched these imported goods along the high roads to the cities of the interior and to the lords of the villas. London was the centre of at least five great high roads. In this respect it was alone among the towns of Roman Britannia. These highways are laid down in Guest’sOrigines Celticæ. They connect the City with every part of the island: on the north-east with Colchester;
  • 70. on the north with Lincoln and York; on the north-west with Uriconium (Wroxeter), for Shrewsbury and Wales and Ireland; on the west with Silchester, for Winchester and Salisbury; on the south-east with Richborough, Dover, and Lympne or Lymne; and on the south with Regnum (Chichester)—if we may fill in the part between London and Dorking which Guest has not indicated. This fact is by itself a conclusive proof that London was the great commercial centre of the island, even if no other proofs existed. And since the whole of the trade was in the hands of the London merchants, we can understand that in times when there was a reasonable amount of security on the road and on the Channel, when the Count of the Saxon Shore patrolled the high seas with his fleet, and the Duke of Britain kept back the Scot and the Pict, the city of Augusta became very wealthy indeed. There were, we have seen, times when there was no safety, times when the pirate did what he pleased and the marauder from the north roamed unmolested about the country. Then the London merchants suffered and trade declined. Thus, when Queen Boadicea’s men massacred the people of London, when the soldiers revolted in the reign of Commodus, when the pirates began their incursions before the establishment of the British fleet, when Carausius used the fleet for his own purposes, and in the troubles which preceded and followed the departure of the legion, there were anxious times for those engaged in trade. But, on the whole, the prosperity of London was continuous for three hundred and fifty years.
  • 71. CHAPTER IV REMAINS OF ROMAN LONDON If one stands in the Museum of the Guildhall and looks round upon the scanty remains of Roman London there exhibited, one feels a cold doubt as to the alleged wealth and greatness of the ancient city. Is this all that has to be shown after an occupation of nearly four hundred years? There is not much more: one may find a room at the British Museum devoted to this subject; and there are a few small private collections containing nothing of importance. Yet when we consider the length of time since Roman London fell; the long history of reconstruction, fire, and successive occupations; the fact that twice—once for more than a hundred years—London was entirely deserted, we must acknowledge that more remains of Roman London than might have been expected. What exists, for instance, of that other great Roman city now called Bordeaux? What, even, of Lutetia Parisiorum? What of Massilia, the most ancient of Gallic cities? There are, however, many remains of Roman London which are not preserved in any collection. Some are above ground; some have been dug up and carried away; some have been disclosed, examined, sketched, and again covered up. Antiquaries have been pleased to find traces of Roman relics of which no memory or tradition remains. Thus, we are assured that there was formerly a Campus Martius in London; its site is said to have been that of the Old Artillery Ground. A temple of Diana is said to have stood on the south side of St. Paul’s. There was a mysterious and extensive crypt called the Camera Dianæ, supposed to have been connected with the worship of that goddess; it was standing in the seventeenth century. Probably it was the crypt of some mediæval house. Stukeley persuaded himself that he found in Long Acre the “magnificent circus, or racecourse, founded by Eli, father of Casvelhun”; he also believed that he had found in Hedge
  • 72. ROMAN ALTAR TO DIANA FOUND IN ST. MARTIN’S-LE-GRAND Lane the survival of the agger or tumulus of King Eli’s grave. The same antiquary preferred to trace Julius Cæsar’s Camp in the Brill opposite old St. Pancras Church. It is sometimes stated that excavations in London have been few and scattered over the whole area of the City; that there has been no systematic and scientific work carried on such as, for instance, was conducted, thirty years ago, at Jerusalem by Sir Charles Warren. But when we consider that there is no single house in the City which has not had half a dozen predecessors on the same site, whose foundations, therefore, have not been dug up over and over again, no one can form any estimate of the remains, Roman, British, and Saxon, which have been dug up, broken up, and carted away. During certain works at St. Mary Woolnoth, for instance, the men came upon vast remains of “rubbish,” consisting of broken pottery and other things, the whole of which were carried off to St. George’s Fields to mend or make the roads there. The only protection of the Roman remains, so long as there was no watch kept over the workmen, lay in the fact that the Roman level was in many places too deep for the ordinary foundations. Thus in Cheapside it was 18 feet below the present surface; in other places it was even more. The collection of Roman antiquities seems to have been first undertaken by John Conyers, an apothecary, at the time of the Great Fire. The rebuilding of the City caused much digging for foundations, in the course of which a great many Roman things were brought to light. Most of these were unheeded. Conyers, however, collected
  • 73. many specimens, which were afterwards bought by Dr. John Woodward. After his death part of the collection was bought by the University of Cambridge; the rest was sold by auction “at Mr. Cooper’s in the Great Piazza, Covent Garden.” Three other early collectors were John Harwood, D.C.L.; John Bagford, a bookseller, who seems to have had some knowledge of coins; and Mr. Kemp, whose collection contained a few London things, especially the two terra-cotta lamps found on the site of St. Paul’s, which were supposed to prove the existence of a temple of Diana at that spot. Burial-places and tombs have been unearthed in various parts of the City, but all outside the walls of the Roman fortress. Thus, they have been found on the site of St. Paul’s, in Bow Lane, Queen Street, Cornhill, St. Dunstan’s Hill, near Carpenter’s Hall, in Camomile Street near the west end of St. Helen’s Church, in King’s Street and Ken Street, Southwark—outside Bishopsgate in “Lollesworth,” afterwards called Spitalfields. The last named was the most extensive of the ancient cemeteries. Stow thus describes it:— “On the East Side of this Churchyard lyeth a large Field, of old time called Lolesworth, now Spittlefield, which about the Year 1576 was broken up for Clay to make Brick: In the digging whereof many earthen Pots called Urnæ were found full of Ashes, and burnt Bones of Men, to wit of the Romans that inhabited here. For it was the custom of the Romans, to burn their Dead, to put their Ashes in an Urn, and then to bury the same with certain Ceremonies, in some Field appointed for that purpose near unto their City.
  • 74. ROMAN BATH, STRAND LANE Every of these pots had in them (with the Ashes of the Dead) one Piece of Copper Money, with the Inscription of the Emperour then reigning: Some of them were of Claudius, some of Vespasian, some of Nero, of Antoninus Pius, of Trajanus, and others. Besides those Urns, many other pots were found in the same place, made of a white Earth, with long Necks and Handles, like to our Stone Jugs: these were empty, but seemed to be buried full of some liquid Matter, long since consumed and soaked through. For there were found divers Phials, and other fashioned Glasses, some most cunningly wrought, such as I have not seen the like, and some of Crystal, all which had Water in them, nothing differing in clearness, taste, or savour from common Spring Water, whatsoever it was at the first. Some of these Glasses had Oil in them very thick, and earthy in savour. Some were supposed to have Balm in them, but had lost the Virtue: Many of these Pots and Glasses were broken in cutting of the Clay, so that few were taken up whole.
  • 75. There were also found divers dishes and cups of a fine red coloured Earth, which shewed outwardly such a shining smoothness, as if they had been of Coral. Those had (in the bottoms) Roman Letters printed, there were also Lamps of white Earth, and red artificially wrought with divers Antiques about them, some three or four Images, made of white earth, about a Span long each of them: One I remember was of Pallas, the rest I have forgotten. I myself have reserved (amongst divers of those Antiquities there found) one Urna, with the Ashes and Bones, and one Pot of white Earth very small, not exceeding the quantity of a quarter of a Wine Pint, made in shape of a Hare, squatted upon her Legs, and between her Ears is the mouth of the pot. There hath also been found (in the same Field) divers Coffins of Stone, containing the Bones of Men: These I suppose to be the Burials of some special Persons, in time of the Britons, or Saxons, after the Romans had left to govern here. Moreover, there were also found the Skulls and Bones of Men, without Coffins, or rather whose Coffins (being of great Timber) were consumed.” (Strype, vol. i. bk. ii. chap. vi.) The description of all the Roman remains found in London would take too long. Let us, however, mention some of the more important (see App. III.). An undoubted piece of Roman work is the old bath still existing in Strand Lane. This bath is too small for public use: it belonged to a private house, built outside London, on the slope of the low hill, then a grassy field, traversed by half a dozen tiny streams. The bath has been often pictured. Many pavements, some of great length and breadth, have been discovered below the surface: of these some have been taken up; some have been drawn. More than forty pavements have been found north of the Thames. These were nearly all on the eastern side of the Walbrook, that side which has always been marked out as the
  • 76. original Roman settlement, and many of them were found within the assumed boundaries of the Roman Prætorium.19 Roman remains have been found under the Tower of Mary-le-Bow Church, where there was a Roman causeway; in Crooked Lane, in Clement’s Lane, in King William Street, in Lombard Street, in Warwick Square, on the site of Leadenhall Market, all along the High Street, Borough as far as St. George’s Church, in Threadneedle Street, Leadenhall Street, Fenchurch Street, Birchin Lane, Lime Street, Lothbury, Gracechurch Street, Eastcheap, Queen Street, Paternoster Row, Bishopsgate Street Within, and many other places. Inscribed stones have also been found in Church Street, Whitechapel, in the Tenter Ground, Goodman’s Fields, Minories, in the Tower of London, at London Wall near Finsbury Circus, in Playhouse Yard, Blackfriars, at Pentonville, on Tower Hill, in Nicholas Lane, Lombard Street, in Hart Street, Crutched Friars. A figure of a youth carrying a bow was found at Bevis Marks. A small altar was dug up in making excavations for Goldsmiths’ Hall. A large number of objects were found in 1837 by dredging the Thames near London Bridge. They were engraved by the Society of Antiquaries, and published by Mr. C. Roach Smith in his Illustrations of Roman London. Among other objects which he has used in illustration of his book are pottery, lamps, bronzes, glass, coins, and utensils of various kinds. A very interesting figure was discovered in Queen Street in 1842. It is described by Mr. W. Chaffers in Archæologia, vol. xxx. p. 543:— “While watching the progress of the excavations recently made in Queen Street, Cheapside (for the formation of a sewer), I was fortunately enabled to obtain possession of several rare and curious specimens of Roman art. A short distance from Watling Street, a fine piece of Roman wall, running directly across the street, was exposed
  • 77. to view in a remarkably perfect condition, built of flat red tiles embedded in solid and compact mortar. Several others, lower down the street, were also discovered. Within a few yards of the wall, one of the bricklayers, removing some earth, struck his trowel against something which he conjectured to be a brass tap; but, on clearing further, he found it was the right heel of the figure, which lay upon its face. The height of the figure, if standing erect, would be 15 inches; but in its stooping posture, the perpendicular height from the base to the crown of the head is only 11 inches. It is evidently intended to represent a person in the attitude of shooting an arrow from a bow. The bow and arrow were probably of richer metal than the figure itself; but no vestiges of them were discovered. The aperture for the bow is seen in the closed left hand, which held it, and the bent fingers of the right appear in the act of drawing the arrow to its full extent previous to its evolation. The eyes are of silver, with the pupils open; the hair disposed in graceful curls on the head, as well as on the chin and upper lip. The left hand, which grasped the bow and sustained the arrow, is so placed as to bring the latter to a level with the eye; and the steadfast look and determined expression of the whole face are much heightened by the silver eyes. It was found at about the depth of between twelve and thirteen feet.” In 1825 a small silver figure of Harpocrates was found in the Thames. It is now in the British Museum. “Early in December 1877 considerable excavations were made at Pie Corner,20 over a space about a 100 feet long and 40 feet broad. At a depth of 11 feet, and at a spot 150 feet, measuring along the houses, from the middle of the great gateway of the hospital, the workmen came upon what they took for two great blocks of stone, which lay half inside the front line of the new building and half under the footway of the street. Continuing their excavation they found that the stones were two great coffins lying side by side, close together. A piece was broken off the lid of each, and in this state, before their contents had been disturbed at all, they were seen by
  • 78. Dr. Dyce Duckworth. In the southern sarcophagus was a leaden case containing a woman’s skeleton. This was disturbed hastily, the workmen being anxious to secure the lead. The other sarcophagus contained two skeletons, a man’s and a woman’s. As these had been somewhat displaced when I saw them half an hour later, I will quote a note which Dr. Duckworth has kindly written to me as to their exact position—‘The female faced west (the mediæval ecclesiastical position), the male faced east (layman’s position).’ The sarcophagi lay very nearly, but not precisely, east and west.” A great many Roman remains were found in 1840 on digging for the foundations of the new Royal Exchange. On the east side of the area there were fragments showing that older buildings had been taken away. In the middle there were found thirty-two cesspools, in some of which were ancient objects. These were cleared out and filled up with concrete. The soil consisted of vegetable earth, accumulation and broken remains of various kinds with gravel at the depth of 16 feet 6 inches. At the western end, however, the workmen came upon the remains of a small building in situ resting on the gravel. The walls of the Old Exchange stood upon this building. When it ceased, oak piles had been driven down and sleepers laid upon the heads of these piles; a rubble wall was discovered below the piles, and under the wall was an ancient pit, sunk 13 feet through the gravel down to the clay. “The pit was irregular in shape, but it measured about 50 feet from north to south, and 34 from east to west, and was filled with hardened mud, in which were contained considerable quantities of animal and vegetable remains, apparently the discarded refuse of the inhabitants of the vicinity. In the same depository were also found very numerous fragments of the red Roman pottery, usually called Samian ware, pieces of glass vessels, broken terra-cotta lamps, parts of amphoræ, mortaria, and other articles made of earth, and all the rubbish which might naturally become accumulated in a pond in the course of years. In this mass likewise occurred a number of Imperial Roman coins, several bronze and iron
  • 79. styles, parts of writing-tables, a bather’s strigil, a large quantity of caliga-soles, sandals, and remains of leather.” (Sir William Tite.) The objects taken out of this pit are catalogued and described by Tite in his volume called Antiquities discovered in Excavating for the Foundations of the New Royal Exchange. Roman pottery, found in Ivy Lane and in St. Paul’s Churchyard, was exhibited at the evening meeting of the L. and Midd. Arch. Soc., Sept. 18, 1860. Roman keys have been found near St. Swithin’s Church, Cannon Street, at Charing Cross beside the statue of Charles I., beneath Gerard’s Hall Crypt, and in the Crypt of St. Paul’s while preparing for the interment of the Duke of Wellington. ROMAN ANTIQUITIES FOUND IN LONDON, 1786 From Archæologia, vol. viii. “An important discovery was made in the year 1835 on the Coleman Street side near the public-house called the Swan’s Nest; here was laid open a pit or well containing a store of earthen vessels of various patterns and capacities. This well had been carefully
  • 80. planked over with thick boards, and at first exhibited no signs of containing anything besides the native gravelly soil, but at a considerable depth other contents were revealed. The vases were placed on their sides longitudinally, and presented the appearance of having been regularly packed or embedded in the mud or sand, which had settled so closely round them that a great number were broken or damaged in being extricated. But those preserved entire, or nearly so, are of the same material as the handles, necks, and pieces of the light-brown coloured vessels met with in such profusion throughout the Roman level in London. Some are of a darker clay approaching to a bluish black, with borders of reticulated work running round the upper part, and one of a singularly elegant form is of a pale-bluish colour with a broad black border at the bottom. Some are without handles, others have either one or two. Their capacity for liquids may be stated as varying from one quart to two gallons, though some that were broken were of much larger dimensions. A small Samian patera, with the ivy-leaf border, and a few figured pieces of the same, were found near the bottom of this well, and also a small brass coin of Allectus, with reverse of the galley, Virtus Aug., and moreover two iron implements resembling a boat-hook and a bucket-handle. The latter of these carries such a homely and modern look, that, had I no further evidence of its history than the mere assurance of the excavators, I should have instantly rejected it, from suspicion of its having been brought to the spot to be palmed off on the unwary; but the fact of these articles being disinterred in the presence of a trustworthy person in my employ disarms all doubt of their authenticity. The dimensions of the pit or well were about 2 feet 9 inches or 3 feet square, and it was boarded on each side with narrow planks about 2 feet long, and 1½ to 2 inches thick, placed upright, but which framework was discontinued towards the bottom of the pit, which merged from a square into an oval form.” (C. Roach Smith in Archæologia, vol. xxix.)
  • 81. ROMAN LONDON x — Sites where Roman pavements and remains have been found. The dotted lines represent streets added at a later date. The following is a list of the more important tessellated pavements which have been discovered in the City:—
  • 82. STATUETTES OF ROMAN DEITIES British Museum. 1661. In Scot’s Yard, Bush Lane, with the remains of a large building. This is supposed to have been an official residence in the Prætorium. Sent to Gresham College. 1681. Near St. Andrew’s, Holborn—deep down. ” Bush Lane, Cannon Street—deep down. 1707. In Camomile Street—5 feet below the surface, with stone walls. 1785, 1786. Sherborne Lane. Four pavements were found here. 1786. Birchin Lane, with remains of walls and pottery, at depth of 9 feet, 12 feet, and 13 feet. 1787. Northumberland Avenue and Crutched Friars—12 feet deep. Society of Antiquaries. 1792. At Poulett House, behind the Navy Pay Office, Great Winchester Street. 1794. Pancras Lane—11 feet deep. 1803. Leadenhall Street—at depth of 9 feet 6 inches. British Museum. 1805. Bank of England, the north-west corner. British Museum. 1805. St. Clement’s Church. 1835. Bank of England, opposite Founders’ Court, and St. Margaret, Lothbury.
  • 83. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com