100% found this document useful (4 votes)
42 views

Instant Download Mastering Jquery 1st Edition Libby Alex PDF All Chapter

Libby

Uploaded by

irolajarrar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
42 views

Instant Download Mastering Jquery 1st Edition Libby Alex PDF All Chapter

Libby

Uploaded by

irolajarrar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Download the full version of the textbook now at textbookfull.

com

Mastering jQuery 1st Edition Libby Alex

https://textbookfull.com/product/mastering-
jquery-1st-edition-libby-alex/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

jQuery UI 1 10 The User Interface Library for jQuery 1st


Edition Libby Alex Wellman Dan

https://textbookfull.com/product/jquery-ui-1-10-the-user-interface-
library-for-jquery-1st-edition-libby-alex-wellman-dan/

textbookfull.com

Learning Less js 1st Edition Libby Alex

https://textbookfull.com/product/learning-less-js-1st-edition-libby-
alex/

textbookfull.com

Beginning SVG: A Practical Introduction to SVG Using Real-


World Examples Alex Libby

https://textbookfull.com/product/beginning-svg-a-practical-
introduction-to-svg-using-real-world-examples-alex-libby/

textbookfull.com

Aid and Development John Overton

https://textbookfull.com/product/aid-and-development-john-overton/

textbookfull.com
Homemade Molasses Bread and Muffins a Cookbook Lovely and
healthy recipes especially for beginners Giorgio M. Vacca

https://textbookfull.com/product/homemade-molasses-bread-and-muffins-
a-cookbook-lovely-and-healthy-recipes-especially-for-beginners-
giorgio-m-vacca/
textbookfull.com

Dyke Swarms of the World A Modern Perspective Rajesh K.


Srivastava

https://textbookfull.com/product/dyke-swarms-of-the-world-a-modern-
perspective-rajesh-k-srivastava/

textbookfull.com

Flat Earth Clues The Sky s The Limit Mark Sargent

https://textbookfull.com/product/flat-earth-clues-the-sky-s-the-limit-
mark-sargent/

textbookfull.com

The Torch Betrayal A Conor Thorn Novel Glenn Dyer

https://textbookfull.com/product/the-torch-betrayal-a-conor-thorn-
novel-glenn-dyer/

textbookfull.com

Multi disciplinary Trends in Artificial Intelligence 8th


International Workshop MIWAI 2014 Bangalore India December
8 10 2014 Proceedings 1st Edition M. Narasimha Murty
https://textbookfull.com/product/multi-disciplinary-trends-in-
artificial-intelligence-8th-international-workshop-
miwai-2014-bangalore-india-december-8-10-2014-proceedings-1st-edition-
m-narasimha-murty/
textbookfull.com
A history of the world s religions Fourteenth Edition.
Edition Blake R. Grangaard

https://textbookfull.com/product/a-history-of-the-world-s-religions-
fourteenth-edition-edition-blake-r-grangaard/

textbookfull.com
www.it-ebooks.info
Mastering jQuery

Elevate your development skills by leveraging every


available ounce of jQuery

Alex Libby

BIRMINGHAM - MUMBAI

www.it-ebooks.info
Mastering jQuery

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: May 2015

Production reference: 1270515

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78398-546-3

www.packtpub.com

www.it-ebooks.info
Credits

Author Project Coordinator


Alex Libby Shipra Chawhan

Reviewers Proofreaders
Islam AlZatary Stephen Copestake
Ilija Bojchovikj Safis Editing
Arun P Johny Joanna McMahon
Lucas Miller
Indexer
Commissioning Editor Tejal Soni
Edward Gordon
Production Coordinator
Acquisition Editors Aparna Bhagat
Vivek Anantharaman
Owen Roberts Cover Work
Aparna Bhagat

Content Development Editor


Shweta Pant

Technical Editor
Tanmayee Patil

Copy Editors
Dipti Kapadia
Jasmine Nadar
Alpha Singh

www.it-ebooks.info
About the Author

Alex Libby has a background in IT support. He has been involved in supporting


end users for almost 20 years in a variety of different environments, and he currently
works as a technical analyst, supporting a medium-sized SharePoint estate for an
international parts distributor who is based in the UK. Although Alex gets to play
with different technologies in his day job, his first true love has always been the open
source movement, and, in particular, experimenting with CSS/CSS3, jQuery, and
HTML5. To date, Alex has already written eight books based on jQuery, HTML5
video, and CSS for Packt Publishing and has reviewed several more. Mastering
jQuery is Alex's ninth book for Packt Publishing.

I would like to thank my family and friends for their support


throughout the process and the reviewers for their valuable
comments; this book wouldn't be what it is without them!

www.it-ebooks.info
About the Reviewers

Islam AlZatary is passionate about new technology in the web industry. He is an


entrepreneur and loves to work with smart teams on good ideas. He has a bachelor's
degree in computer information system. He has worked for 2 years as a PHP web
developer and then he was appointed as a Sr. frontend engineer in 2010.

He deals with jQuery, jQuery UI, HTML/HTML5, CSS/CSS3, the Bootstrap


framework, the Mailer template, JavaScript frameworks (RequireJS and AngularJS),
and all design approaches. He also likes the mobile-first approach, Magento,
e-commerce solutions, and creating his own CSS framework called Lego.

He has reviewed jQuery UI 1.10: The User Interface Library for jQuery, Packt Publishing.

He can be found at http://www.islamzatary.com. On Twitter, he can be found


at https://twitter.com/islamzatary. You can also find him on LinkedIn
and Facebook.

www.it-ebooks.info
Ilija Bojchovikj is a talented senior manager of user experience design and
development with the proven know-how to combine creative and usability
viewpoints resulting in world-class web and mobile applications and systems.
He has more than 4 years of experience in partnering with internal and external
stakeholders to discover, build, improve, and expand the user experience and create
and develop outstanding user interfaces.

He has a proven history of creating cutting edge interface designs and information
architectures for websites and mobile applications through a user-centered design
process by constructing screen flows, prototypes, and wireframes.

He believes in the power of the Web and those who make it what it is by making and
sharing for the sake of betterment; by creating amazing, passionate, and empathetic
communities; and by improving the human condition through it all. High five,
people of the Web!

You can see what Ilija's up to at http://Bojchovikj.com or on Twitter at @il_337.

I'd like to thank the countless people who've given me opportunities


and been my inspiration, teachers, sounding boards, my beautiful
girlfriend, Monika, and friends. I won't list names because that's just
boring and irrelevant for anyone else. Some of you know who you
are, others may not. If I've argued passionately with you about the
minutiae of nerdy stuff, you're likely to be on the list.

www.it-ebooks.info
Arun P Johny is a dynamic and competent professional of Web application
development with a bachelor's degree in computer application from Kristu Jayanti
College, Bangalore. He has been involved in software development for more than
8 years. He is one of the main contributors in Stack Overflow for JavaScript/jQuery
questions.

For more than 8 years, he has been associated with Greytip Software Pvt Ltd
where he is currently spearheading efforts as the tech lead in charge of developing
Greytip Online—the leading online payroll and HR software in India. He focuses on
developing a highly scalable and available web application using technologies that
are as varied as Java, Spring, and memcache to JavaScript.

Arun has experience in all aspects of software engineering, which include software
design, systems architecture, application programming, and testing. He has a vast
product development experience in Java, jQuery, Spring, Hibernate, PostgreSQL,
and many other enterprise technologies. Arun is skilled in other techniques such
as Twitter Bootstrap, AngularJS, ExtJS, FreeMarker, Maven, Spring Security, Git,
Activiti, Quartz Scheduler, Eclipse BIRT, and Agile methodology.

Arun loves problem solving and really enjoys brainstorming unique solutions. He
can be reached at arunpjohny@gmail.com. You can also get in touch with him at
https://in.linkedin.com/in/arunpjohny.

I'm greatly thankful to my family members and colleagues for their


support and motivation to review this book.

Lucas Miller, Internet Plumber, works as a programmer, designer, and cofounder


for the jack-of-all-trades media design group RUST LTD (http://rustltd.
com/). He likes long walks on the beach, piña coladas, and getting caught in long
conversations about the nuances of typeface decisions in popular media. When
he isn't developing websites or making games, he can be found teaching, wolf-
wrangling, or pursuing whichever new and exciting opportunity presents itself to
him that day.

You can find him at http://lucas.rustltd.com/.

www.it-ebooks.info
www.PacktPub.com

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.com
and as a print book customer, you are entitled to a discount on the eBook copy. Get in
touch with us at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters and receive exclusive discounts and offers on Packt
books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view 9 entirely free books. Simply use your login credentials for
immediate access.

www.it-ebooks.info
Table of Contents
Preface ix
Chapter 1: Installing jQuery 1
Downloading and installing jQuery 1
Using jQuery in a development capacity 2
Adding the jQuery Migrate plugin 3
Using a CDN 4
Using other sources to install jQuery 4
Using NodeJS to install jQuery 5
Installing jQuery using Bower 6
Using the AMD approach to load jQuery 9
Customizing the downloads of jQuery from Git 11
Removing redundant modules 13
Using a GUI as an alternative 14
Adding source map support 14
Adding support for source maps 16
Working with Modernizr as a fallback 16
Best practices for loading jQuery 18
Summary 19
Chapter 2: Customizing jQuery 21
Getting prepared 22
Patching the library on the run 22
Introducing monkey patching 22
Replacing or modifying existing behaviors 23
Creating a basic monkey patch 24
Dissecting our monkey patch 26
Considering the benefits of monkey patching 28

[i]

www.it-ebooks.info
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Table of Contents

Updating animation support in jQuery 29


Exploring the requestAnimationFrame API's past 30
Using the requestAnimationFrame method today 30
Creating our demo 30
Adding WebP support to jQuery 34
Getting started 34
Creating our patch 35
Taking things further 39
Considering the pitfalls of monkey patching 41
Distributing or applying patches 42
Summary 44
Chapter 3: Organizing Your Code 45
Introducing design patterns 46
Defining design patterns 46
Dissecting the structure of a design pattern 48
Categorizing patterns 49
The Composite Pattern 49
Advantages and disadvantages of the Composite Pattern 50
The Adapter Pattern 51
Advantages and disadvantages of the Adapter Pattern 51
The Facade Pattern 52
Creating a simple animation 53
Advantages and disadvantages of the Façade Pattern 54
The Observer Pattern 55
Advantages and disadvantages of the Observer Pattern 56
Creating a basic example 57
The Iterator Pattern 58
Advantages and disadvantages of the Iterator Pattern 60
The Lazy Initialization Pattern 61
Advantages and disadvantages of the Lazy Initialization Pattern 61
The Strategy Pattern 62
Building a simple toggle effect 63
Switching between actions 64
Advantages and disadvantages of the Strategy Pattern 64
The Proxy Pattern 65
Advantages and disadvantages of the Proxy Pattern 66
Builder Pattern 67
Advantages and disadvantages of the Builder Pattern 68
Exploring the use of patterns within the jQuery library 69
Summary 72

[ ii ]

www.it-ebooks.info
Table of Contents

Chapter 4: Working with Forms 73


Exploring the need for form validation 74
Creating a basic form 75
Starting with simple HTML5 validation 76
Using HTML5 over jQuery 78
Using jQuery to validate our forms 79
Validating forms using regex statements 81
Creating a regex validation function for e-mails 82
Taking it further for URL validation 83
Building a simple validation plugin 84
Developing a plugin architecture for validation 88
Creating our basic form 89
Creating custom validators 90
Localizing our content 94
Centralizing our error messages 95
Wrapping up development 96
Noting the use of best practices 97
Providing fallback support 98
Creating an advanced contact form using AJAX 99
Developing an advanced file upload form using jQuery 102
Summary 104
Chapter 5: Integrating AJAX 107
Revisiting AJAX 108
Defining AJAX 109
Creating a simple example using AJAX 110
Improving the speed of loading data with static sites 113
Using localStorage to cache AJAX content 115
Using callbacks to handle multiple AJAX requests 117
Enhancing your code with jQuery Deferreds and Promises 118
Working with Deferreds and Promises 120
Modifying our advance contact form 122
Adding file upload capabilities using AJAX 125
Examining the use of Promises and Deferreds in the demo 127
Detailing AJAX best practices 128
Summary 129
Chapter 6: Animating in jQuery 131
Choosing CSS or jQuery 132
Controlling the jQuery animation queue 134
Fixing the problem 135

[ iii ]

www.it-ebooks.info
Table of Contents

Making the transition even smoother 136


Using a pure CSS solution 138
Improving jQuery animations 139
Introducing easing functions 140
Designing custom animations 141
Converting to use with jQuery 143
Implementing some custom animations 145
Animating rollover buttons 145
Exploring the code in more detail 146
Animating an overlay effect 147
Animating in a responsive website 149
Considering animation performance on responsive sites 152
Handling animation requests on a responsive site 154
Animating content for mobile devices 157
Improving the appearance of animations 159
Implementing responsive parallax scrolling 161
Building a parallax scrolling page 161
Considering the implications of parallax scrolling 164
Summary 166
Chapter 7: Advanced Event Handling 167
Introducing event handling 167
Delegating events 168
Revisiting the basics of event delegation 168
Reworking our code 170
Supporting older browsers 170
Exploring a simple demonstration 171
Exploring the implications of using event delegation 172
Controlling delegation 173
Using the stopPropagation() method as an alternative 175
Using the $.proxy function 177
Creating and decoupling custom event types 180
Creating a custom event 181
Working with the Multiclick event plugin 183
Namespacing events 184
Summary 187
Chapter 8: Using jQuery Effects 189
Revisiting effects 189
Exploring the differences between animation and effects 190
Creating custom effects 190
Exploring the animate() method as the basis for effects 191

[ iv ]

www.it-ebooks.info
Table of Contents

Putting custom effects into action 192


Creating a clickToggle handler 192
Sliding content with a slide-fade Toggle 194
Applying custom easing functions to effects 196
Adding a custom easing to our effect 197
Using Bezier curves in effects 199
Adding Bezier curve support 200
Using pure CSS as an alternative 202
Adding callbacks to our effects 204
Controlling content with jQuery's Promises 205
Creating and managing the effect queue 207
Summary 209
Chapter 9: Using the Web Performance APIs 211
An introduction to the Page Visibility API 211
Supporting the API 212
Implementing the Page Visibility API 212
Breaking down the API 214
Detecting support for the Page Visibility API 214
Providing fallback support 217
Installing visibility.js 217
Building the demo 218
Using the API in a practical context 220
Pausing video or audio 220
Adding support to a CMS 221
Exploring ideas for examples 223
Introducing the requestAnimationFrame API 224
Exploring the concept 225
Viewing the API in action 226
Using the requestAnimationFrame API 226
Retrofitting the changes to jQuery 227
Updating existing code 228
Some examples of using requestAnimationFrame 229
Creating a scrollable effect 229
Animating the Google Maps marker 231
Exploring sources of inspiration 232
Summary 233
Chapter 10: Manipulating Images 235
Manipulating colors in images 235
Adding filters using CSS3 236
Getting ready 237
Creating our base page 237

[v]

www.it-ebooks.info
Table of Contents

Changing the brightness level 240


Adding a sepia filter to our image 240
Exploring other filters 241
Blending images using CSS3 242
Applying filters with CamanJS 244
Introducing CamanJS as a plugin 244
Building a simple demo 244
Getting really creative 246
Creating simple filters manually 248
Grayscaling an image 249
Adding a sepia tone 251
Blending images 253
Animating images with filters 255
Introducing cssAnimate 255
Creating a signature pad and exporting the image 258
Capturing and manipulating webcam images 260
Finishing up 265
Summary 265
Chapter 11: Authoring Advanced Plugins 267
Detecting signs of a poorly developed plugin 267
Introducing design patterns 269
Creating or using patterns 270
Designing an advanced plugin 271
Rebuilding our plugin using boilerplate 272
Converting animations to use CSS3 automatically 276
Working with CSS-based animations 278
Considering the impact of the change 279
Falling back on jQuery animations 280
Extending our plugin 282
Packaging our plugin using Bower 283
Automating the provision of documentation 285
Returning values from our plugin 286
Exploring best practices and principles 289
Summary 291
Chapter 12: Using jQuery with the Node-WebKit Project 293
Setting the scene 294
Introducing Node-WebKit 294
Operating HTML applications on a desktop 295
Preparing our development environment 297

[ vi ]

www.it-ebooks.info
Table of Contents

Installing and building our first application 299


Dissecting the package.json file 301
Building our simple application 302
Exploring our demo further 304
Dissecting our content files 304
Exploring window.js 305
Dissecting the BlueImp plugin configuration 305
Automating the creation of our project 308
Debugging your application 310
Packaging and deploying your app 310
Creating packages manually 311
Automating the process 311
Deploying your application 314
Taking things further 316
Summary 317
Chapter 13: Enhancing Performance in jQuery 319
Understanding why performance is critical 320
Monitoring the speed of jQuery using Firebug 321
Automating performance monitoring 324
Gaining insight using Google PageSpeed 330
Linting jQuery code automatically 332
Minifying code using NodeJS 335
Exploring some points of note 337
Working through a real example 338
Working out unused JavaScript 339
Implementing best practices 342
Designing a strategy for performance 347
Staying with the use of jQuery 349
Summary 350
Chapter 14: Testing jQuery 351
Revisiting QUnit 351
Installing QUnit 352
Creating a simple demo 352
Automating tests with QUnit 356
Exploring best practices when using QUnit 360
Summary 362
Index 363

[ vii ]

www.it-ebooks.info
www.it-ebooks.info
Preface
Imagine a scenario, if you will, where you're an intermediate-level developer,
reasonably au fait with writing code, who feels that there should be more to
developing jQuery than just punching keys into a text editor.

You'd be right; anyone can write code. To take that step towards being a more
rounded developer, we must think further afield. Gone are the days of writing
dozens of chained statements that take a degree to understand and debug, and
in their place are the decisions that help us make smarter decisions about using
jQuery and that make more effective use of time in our busy lives.

As an author, I maintain that simple solutions frequently work better than complex
solutions; throughout this book, we'll take look at a variety of topics that will help
develop your skills, make you consider all the options, and understand that there is
more to writing jQuery code.

It's going to be a great journey, with more twists and turns than a detective novel;
the question is, "Are you ready?" If the answer is yes, let's make a start…

What this book covers


Chapter 1, Installing jQuery, kicks off our journey into the world of mastering jQuery,
where you will learn that there is more to downloading and installing jQuery than
simply using CDN or local links. We'll take a look at how to install jQuery using
package managers, how we can customize the elements of our download, as well
as how to add source maps and more to help fine-tune our copy of the library.

Chapter 2, Customizing jQuery, takes things further—you may find that the elements
of jQuery don't quite work the way you want. In this chapter, we'll take a look at
how you can create and distribute patches that can be applied temporarily in order
to extend or alter the core functionality within jQuery.

[ ix ]

www.it-ebooks.info
Preface

Chapter 3, Organizing Your Code, explores the use of jQuery design patterns, which
is a useful concept in maintaining well-organized code that makes developing and
debugging easier. We'll take a look at some examples of patterns and how they fit
in with jQuery.

Chapter 4, Working with Forms, takes a look at the doyen of form functionality -
validating responses on forms. We'll explore how you can be more effective at form
validation, before using it to great effect in a contact form that employs AJAX, and
develop a file upload form.

Chapter 5, Integrating AJAX, examines how we can improve the speed of loading
data on static sites, with the use of callbacks to help manage multiple AJAX requests.
We'll take a look at AJAX best practices and explore how best to manage these
requests through the use of jQuery's Deferreds and Promises functionalities.

Chapter 6, Animating in jQuery, takes us on a journey to discover how we can be


smarter at managing animations within jQuery, and explores how best to manage
the jQuery queue to prevent animation build-ups. We'll also learn how we can
implement custom animations and why jQuery isn't always the right tool to use in
order to move elements on a page.

Chapter 7, Advanced Event Handling, examines how many developers may simply
use .on() or .off() to handle events, but you'll see that there is more to using these
methods, if you really want to take advantage of jQuery. We'll create a number of
custom events before we explore the use of event delegation to better manage when
these event handlers are called in our code.

Chapter 8, Using jQuery Effects, continues our journey, with a quick recap on using
effects in jQuery, as we explore how we can create custom effects with callbacks and
learn how to better manage the queue that forms the basis of their use within jQuery.

Chapter 9, Using the Web Performance APIs, starts the second part of the book, where
we explore some of the more interesting options available to us when using jQuery.
In this chapter, we'll discover how to use the Page Visibility API with jQuery and
see how we can use it to provide a smoother appearance, reduce resources, and still
maintain complex animations on our pages. Intrigued? You will be, when you visit
this chapter!

Chapter 10, Manipulating Images, illustrates how, with the use of jQuery and some
reasonably simple math, we can apply all kinds of effects to images. We can perform
something as simple as blurring images to creating custom effects. We'll then use
some of these techniques to create a simple signature page that exports images, and
apply all kinds of effects to images extracted from your own webcam.

[x]

www.it-ebooks.info
Preface

Chapter 11, Authoring Advanced Plugins, covers one of the key topics of using jQuery:
creating and distributing plugins. With more and more functionality being moved
to using plugins, we'll cover some of the tips and tricks behind creating your own
plugins; you'll see that there is more to it than just writing code!

Chapter 12, Using jQuery with the Node-WebKit Project, explores an interesting library
that takes the best elements of Node, JavaScript/jQuery, CSS, and plain HTML
and combines them into something that blurs the boundaries between desktops
and the online world. We'll work through some existing online code and convert
it for use as a desktop application, before packaging it and making it available for
download online.

Chapter 13, Enhancing Performance in jQuery, takes you through some of the
considerations, tips, and tricks that you need to use in order to optimize and enhance
the performance of your code. You'll see how easy it is to get the basics from DOM
inspectors, such as Firebug, right through to automating your tests with Grunt, and
finally developing a strategy to keep monitoring the performance of your code.

Chapter 14, Testing jQuery, is the concluding chapter in our journey through the
world of mastering jQuery, where we will take a look at testing our code using
QUnit and how we can take advantage of Grunt to automate an otherwise routine
but important task within the world of developing with jQuery.

What you need for this book


All you need to work through most of the examples in this book is a simple text
or code editor, a copy of the jQuery library, Internet access, and a browser. I
recommend that you install Sublime Text—either version 2 or 3; it works well
with Node and Grunt, which we will use at various stages throughout the book.

Some of the examples make use of additional software, such as Node or


Grunt—details are included within the appropriate chapter along with links
to download the application from its source.

Who this book is for


The book is for frontend developers who want to do more than just write code, but
who want to explore the tips and tricks that can be used to expand their skills within
jQuery development. To get the most out of this book, you should have a good
knowledge of HTML, CSS, and JavaScript and ideally be at an intermediate level
with jQuery.

[ xi ]

www.it-ebooks.info
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Preface

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text are shown as follows: "We'll start by extracting the relevant files
from the code download for this book; for this demo, we'll need clicktoggle.css,
jquery.min.js, and clicktoggle.html."

A block of code is set as follows:


$(this).on("click", function() {
if (clicked) {
clicked = false;
return b.apply(this, arguments);
}
clicked = true;
return a.apply(this, arguments);
});
});

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
$('#section').hide(2000, 'swing', function() {
$(this).html("Animation Completed");
});

Any command-line input or output is written as follows:


npm install jquery

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "When
we view the page and select the Images tab, after a short delay we should see six
new images."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

[ xii ]

www.it-ebooks.info
Preface

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book – what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to feedback@packtpub.com,


and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send
us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
suggest@packtpub.com.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer Support
Now that you are the proud owner of a Packt book, we have a number of things
to help you get the most from your purchase.

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to have
the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes
do happen. If you find a mistake in one of our books – maybe a mistake in the text
or the code – we would be grateful if you would report this to us. By doing so, you
can save other readers from frustration and help us to improve subsequent versions
of this book. If you find any errata, please report them by visiting http://www.
packtpub.com/support, selecting your book, clicking on the Errata Submission
Form link, and entering the details of your errata. Once your errata are verified,
your submission will be accepted and the errata will be uploaded on our website,
or added to any list of existing errata, under the Errata section of that title.

[ xiii ]

www.it-ebooks.info
Preface

To view the previously submitted errata, go to https://www.packtpub.com/books/


content/support and enter the name of the book in the search field. The required
information will appear under the Errata section.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we can
pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.

[ xiv ]

www.it-ebooks.info
Installing jQuery
Local or CDN, I wonder…? Which version…? Do I support old IE…?

Installing jQuery is a thankless task that has to be done countless times by any
developer—it is easy to imagine that person asking some of the questions that start
this chapter. It is easy to imagine why most people go with the option of using a
Content Delivery Network (CDN) link, but there is more to installing jQuery
than taking the easy route!

There are more options available, where we can be really specific about what
we need to use—throughout this chapter, we will examine some of the options
available to help develop your skills even further. We'll cover a number of topics,
which include:

• Downloading and installing jQuery


• Customizing jQuery downloads
• Building from Git
• Using other sources to install jQuery
• Adding source map support
• Working with Modernizr as a fallback

Intrigued? Let's get started.

Downloading and installing jQuery


As with all projects that require the use of jQuery, we must start somewhere—no
doubt you've downloaded and installed jQuery a thousand times; let's just quickly
recap to bring ourselves up to speed.

[1]

www.it-ebooks.info
Installing jQuery

If we browse to http://www.jquery.com/download, we can download jQuery


using one of the two methods: downloading the compressed production version or
the uncompressed development version. If we don't need to support old IE (IE6, 7,
and 8), then we can choose the 2.x branch. If, however, you still have some diehards
who can't (or don't want to) upgrade, then the 1.x branch must be used instead.

To include jQuery, we just need to add this link to our page:


<script src="http://code.jquery.com/jquery-X.X.X.js"></script>

Downloading the example code


You can download the example code files for all Packt books you have
purchased from your account from http://www.packtpub.com. If you
purchase this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the files e-mailed directly to you.

Here, X.X.X marks the version number of jQuery or the Migrate plugin that is being
used in the page.

Conventional wisdom states that the jQuery plugin (and this includes the Migrate
plugin too) should be added to the <head> tag, although there are valid arguments
to add it as the last statement before the closing <body> tag; placing it here may help
speed up loading times to your site.

This argument is not set in stone; there may be instances where placing it in
the <head> tag is necessary and this choice should be left to the developer's
requirements. My personal preference is to place it in the <head> tag as it provides
a clean separation of the script (and the CSS) code from the main markup in the
body of the page, particularly on lighter sites.

I have even seen some developers argue that there is little perceived difference
if jQuery is added at the top, rather than at the bottom; some systems, such as
WordPress, include jQuery in the <head> section too, so either will work. The key
here though is if you are perceiving slowness, then move your scripts to just before
the <body> tag, which is considered a better practice.

Using jQuery in a development capacity


A useful point to note at this stage is that best practice recommends that CDN links
should not be used within a development capacity; instead, the uncompressed files
should be downloaded and referenced locally. Once the site is complete and is ready
to be uploaded, then CDN links can be used.

[2]

www.it-ebooks.info
Random documents with unrelated
content Scribd suggests to you:
At this point Ben stepped around the barrier of boughs and into the
circle of light cast by the fire. The sandy-haired youth leaped up and
seized a cudgel which was lying beside him; whirling it about his
head, he cried boldly enough:
“Stop where you are, or by this and by that, you’ll have this lump of
a stick clattering about the head of you!”
Ben stood smilingly regarding him.
“How did you make your way all the distance without being found
out?”
The other, seeing that, at least, no immediate attack was meditated,
lowered his bludgeon.
“What’s that you say?” he demanded.
“I ask you, how did you get so far from Trenton without being
discovered?”
“From Trenton, is it?” cautiously. “And, sure, who told you I come
from Trenton?”
“The clothes you wear,” said Ben, as he sat down upon a log. “You
threw the coat away because it was red; but the other things tell
just as plainly that you are a British soldier.”
Here the cudgel was grasped firmly once more, and the sandy-
haired lad took a step forward.
“Is it me that you call such a name?” demanded he. “Is it Paddy
Burk that you call by so disgraceful a title? True for you, I did wear
the red coat, and true again that I threw it in a ditch—because I
hated it. But never was I a British soldier. I was an Irish boy
compelled to wear a British soldier’s clothes, but never for a minute
was I anything less.”
“You are a deserter, then,” said Ben.
“I left them just as honestly as they enlisted me. There was I at
home, a raw boy, knowing nothing and listening to the tales the
dragoon sergeant told of foreign parts. And when he handed me the
‘shilling,’ I took it thinking he only meant to be generous with me,
and never dreaming that it made me a redcoat.”
“I’ve heard that they do such things,” said Ben.
“And then off they took me,” lamented Paddy Burk. “Off they took
me to a big town and put me on board a ship with dozens more like
me, and over we came to America as British soldiers—a thing we
never thought to be.”
“You were with the army of Cornwallis, I suppose,” said Ben.
“Yes,” replied the other. “I was with him till he reached the place
where they tried to cross the bridge, and the Americans drove them
back. It was yesterday, I think. Then I got a good chance and took
leg bail for it across the river on the ice. And,” with feeling, “here I
am wandering about with never a bite nor sup since then; and it’s
fair weak with the hunger I am.”
There was a moment’s silence, then Ben Cooper spoke.
“You don’t like the British service, then?”
“Like it!” The sandy-haired lad gripped his cudgel in both hands.
“Sure, and how could any one with Irish blood in his veins like it?”
“Perhaps,” said Ben, “you’d prefer that of America.”
The cudgel was lowered and an interested look appeared upon the
face of the boy.
“Now that,” said he, “is a different thing. I would have tried to find
General Washington’s army, but I was afeered to go back across the
river.” He stared at Ben, anxiously. “Maybe now it’s yourself that
could tell me how to find it.”
“Well,” said Ben, “one of the first things that should be done in your
case is to get you warm and provide you with some food. Then we
can think of the rest.”
The face of the Irish boy brightened up wonderfully.
“Arrah, then it’s the great lad ye are!” he cried, with admiration.
“Sure, a bite to eat and a fire with a trifle of heat in it would be as
welcome as the sun in the morning.”
“But,” proceeded Ben, “before I can do anything else, I must first
see to a matter of great importance. As for you,” and he pointed in
the direction of the road, “take that way until you come to an inn,
less than a mile away. Say to the landlady that——”
Here the other interrupted him.
“Ah, sure, it would make no matter what I’d say to her. It would be
all the same, faith. She’d up with the broom and drive me away from
the door for a vagabond.”
“But——” said Ben, and again he was interrupted.
“Wherever you do be going,” said Paddy Burk, “let me go with you;
and when we come to a place where there’s a bit of comfort to be
had, sure, then, you can speak for me yourself.”
Seeing that the lad was fixed in his belief that no one would receive
him if his plea were unsupported, Ben’s mind was instantly made up.
“Come, then,” said he, arising, “and make yourself ready for a little
adventure.”
“Ah,” said Paddy Burk, and he passed his hand lovingly over the
length of his stout club, “that would be another name for a ‘ruction,’
I’m thinking. Well, by this and by that, when there’s such to the fore,
no one ever saw Paddy Burk stand back and look on.”
Ben laughed.
“Perhaps, Paddy,” said he, “you’ll get your fill of ‘ructions,’ as you call
them; for there is something ahead which promises well in that
direction.”
In a few moments they had put out the fire and were trudging away
under the trees, the wind whirling the snow about their faces and
into their eyes. Ben kept his bearings and never allowed himself to
get far from the road; indeed, he skirted it very closely, his
companion trudging along at his side.
Suddenly the latter said:
“Whist! What is that beyant there? Is it a house, I dunno, or is it
somebody carrying a light?”
At almost the same moment Ben had perceived the dim spark
through the falling snow.
“It is moving,” said he, “and that shows that it is a light that is being
carried.” They paused for a time and watched the spark.
“It is slowly growing brighter,” commented Ben, “and that proves
that it is coming toward us.”
A little more observation showed that the light must be upon the
road.
“Many’s the time I’ve seen the lights coming on that way on the
night before market day at Ballysampson,” said Paddy Burk. “They’d
move a weeny bit this way, and a small bit that way, according to
the turns in the road, and all the time they’d be a-blinking like a
one-eyed dragon out of a fairy book.”
Ben, with a sharp intaking of the breath, drew out his pistols. The
other perceived the action in the dim light thrown up by the snow.
“Ah, ha,” said he, “and so here is where the ruction starts. Well,”
with a brisk whirl of his cudgel, “the sooner the better, for a trifle of
exercise would warm me, so it would.”
“The first point I must warn you on is to keep silence,” said Ben, one
hand uplifted. “A wagon or carriage is expected at any time, bearing
matters of moment for the American camp. I have reason to think
that it is to be stopped near here.”
“And you think,” said Paddy Burk, in a whisper, “that this, with the
light, may be the carriage?”
“I do,” replied Ben Cooper. “But come, let us make our way to the
roadside.”
They turned at a sharp angle and started for the road; and as they
reached it there came a sudden shout; a pistol shot rang out, and
the moving lamp came to a stand far down the snowy road.
With the pistols gripped in his hands, Ben ran forward; as he neared
the halted vehicle, he saw a man climbing down from a high seat,
and another holding a pistol at his head. In the snow lay a dark,
huddled form, and over it stood a man in a long greatcoat, his hands
stuffed into his pockets.
“Have mercy, good folk,” whined the man, climbing down from the
driver’s seat. “Take pity upon one who never did you harm.”
The man with the pistol answered with a brutal kick, at which the
other howled loudly.
“Now hold your tongue, or you’ll get worse than that,” said the man
with the pistol.
“The money is here—safe in the bags,” cried the coward. “Don’t
harm me and I will show you where to find it.”
He was creeping toward the carriage once more when Ben Cooper’s
first pistol exploded, and missed. The man who had kicked the driver
whirled about savagely, but the second pistol laid him low; then the
youth dropped both empty weapons in the road and leaped for the
man in the greatcoat.
This person, however, stepped back, so as to avoid the full force of
the rush; then he lifted an empty pistol which he held in his hand,
and dropped it skilfully upon the boy’s head. Ben staggered beneath
the shock of the blow; the pistol lifted to repeat, but the lad, shaken
though he was, dodged, and in another instant had seized the other
round the body.
The man in the greatcoat was powerfully made, and did not hesitate
to grapple with his foe; but in spite of his great strength he found in
the boy a supple, eel-like quality that made him difficult to master.
Then to make matters worse for him, he stumbled over the prostrate
form in the road and went down with the boy upon him. In an
instant Ben had planted a knee in his chest, and gripped him about
the throat.
All this had taken but a moment; and as Ben clung to his antagonist
he felt a glow of triumph. But in this he was premature, for just then
the man who had gone down under his pistol shot arose to his feet,
the blood streaming from a wound in his scalp, and lurched toward
the boy. It would have gone hard with the latter had not fortune
favored him that night. Cramped by the cold and weakened by
hunger, Paddy Burk had labored along a score or more paces in the
rear. But now, as the newly arisen man was dragging Ben Cooper
from the one he held pinned to the ground, the Irish lad was upon
him with a whoop; the cudgel twirled gaily and the man dropped to
the road once more.
“Up on the seat with you,” directed Paddy, glaring at the driver.
But the speaker’s face looked so distorted in the dim lantern light
that the driver was stricken with fear and could not move.
“Then I’ll up for you,” said Paddy, promptly. “Inside with you,” to
Ben, who stood still dazed from the blow he had received; “and as
for you,” pointing his bludgeon at the man with the greatcoat, who
was scrambling out of the snow, “keep your distance, or by this and
by that, I’ll give you a taste of the stick that you’ll not like.”
With that he leaped upon the seat of the vehicle, and grasped the
reins; Ben, after a bewildered glance within that showed him a heap
of canvas bags snugly tucked away in a corner, stumbled in and
dropped upon a seat. Then with a yell at the now plunging horses,
the Irish lad waved his cudgel above his head.
“Away with you, my beauties,” he cried; “sure it is mesilf that will
give you a loose rein all the way to General Washington’s camp if
need be.”
And so away they tore with their precious load, the lantern swaying
madly, the carriage pitching from side to side.
CHAPTER IX
DEALS WITH THE ARRIVAL OF GILBERT
MOTIER,
MARQUIS DE LAFAYETTE

The dawn was well past when Ben Cooper and Paddy Burk dashed
up before the Freemasons Tavern at Morristown in the carriage
containing the fifty thousand dollars in silver and gold coin sent by
Robert Morris. Word was at once carried to the commander-in-chief
by the officer in charge; then the bags were carried into the building
and placed safely under guard.
General Washington was at breakfast some hours later when Ben
and the Irish lad were sent in, in response to his request. He
received Ben kindly and thanked him with the utmost warmth for his
gallant conduct. The lad, when given the opportunity, told Paddy
Burk’s story as to how he was impressed into the British army, of his
desertion, and of his rare courage in the rescue of the money bags.
“If it had not been for him, Your Excellency,” said young Cooper, “all
that I attempted would have gone for nothing. He’s one of the
bravest fellows I ever saw, and,” eagerly, “he would like to join with
us against the British.”
Paddy’s hand went to his forelock by way of salute.
“It’s not like as if I were playing the traitor to them, your honor,” he
said. “For sorra the one of them had any right to me; they got me by
deception, and if I made away from them by the same means, small
blame to me.”
The commander smiled.
“Do you desire to join with us?” he asked.
“I do, if you please, your honor—that is, if I can join the troop that
Misther Cooper is with, sir.”
“I dare say it can be arranged,” smiled the general. “You seem to be
of the character needed for a scout and courier.” He turned to an
officer near by. “Attend to this, Harrison, if you please.”
The general’s secretary accordingly led the Irish lad out of the inn;
and before long he was duly added to the scouts in the service of
headquarters. Nat Brewster, Ezra and George Prentiss and the
Porcupine took to their new comrade at once; and his shrewd
sayings, comical manners and quaint songs added to the good
feeling the more they saw of him.
After this there were no large movements for a long time;
Washington established posts completely across the Jerseys,
connecting with the forts on the Hudson highlands. The temporary
halting place proved to be just the spot for a winter quarters, and
being almost equally near to Amboy, Brunswick and Newark, was a
most excellent place from which to carry on a system of forays, raids
and other harassing movements; the hills and dense forests afforded
an almost complete protection from counter attacks of a serious
nature.
Slowly the winter wore on; brilliant exploits marked it from time to
time; the American troops became a terror to the British, who were
not only driven out of the Jerseys, but were compelled to keep to
one or two very narrowly defined districts.
The British government was making vast preparations for the coming
campaign in the spring, however. More Hessians were being brought
to take the place of those captured at Trenton. Burgoyne was
coming to head a powerful army which was to invade the country
from Canada; General Howe and his brother, the admiral, were
formulating a scheme which would give them Philadelphia, while Sir
Henry Clinton spent the time planning an ascent of the Hudson and
a blow at the Highland forts. If these latter could be taken and the
stronghold at West Point passed, Clinton could join his army to that
of Burgoyne and so split the struggling states in two, neither part of
which could lend help to the other.
When Howe began to show signs of life, Washington broke up his
camp at Morristown, and took up a position at Middlebrook, where
he would be more in touch with the movements of that leader. Once
Howe tried to engulf Sullivan at Princeton; again he endeavored to
tempt Washington to try a general engagement. But in neither of
these did he succeed, and so he began to plan once more with the
admiral for the taking of Philadelphia.
During this period Ben Cooper saw quite a little of Philadelphia life.
The business of the army frequently took him there, and often he
had permission to spend some little time.
Distinguished foreigners, attracted by the struggle for independence,
were pouring into the city; public and social circles were besieged by
them; demands, highly preposterous for the most part, were made
by heretofore unknown persons for commissions; men who had not
been of higher grade than captain in the armies of Europe now
treated with contempt any suggestion save that which carried with it
the rank, at least, of general of brigade.
During the early summer Ben was enjoying a fortnight’s leave of
absence with his father at Germantown; and one day he received a
letter from Miss Betsy Claflin. He had met the Claflins frequently
since the night at the inn at Burlington, and had become very
intimate with them all.
“We are to give a very grand dinner at the City Tavern,” wrote Betsy,
“and we are to have such a number of distinguished people present
that I shall be dreadfully frightened, I know. And so I shall need all
my friends to give me courage, and feel sure that I can count upon
you for one.”
There was a great deal more to the note, telling him the names of
the notables who were to grace the feast, not the least among
whom was Washington himself. The time set was but a few nights
off, and Miss Betsy apologized for the lateness of the invitation
because: “I had not known but that you were with the army,
otherwise this would have reached you much sooner.”
The City Tavern was the fashionable place of the city at that day,
and many splendid affairs were held between its walls; and so, when
the night arrived, Ben spent a great deal of time over his toilet, and
made his way with much magnificence to the inn. It was brilliantly
lighted; there appeared to be candles everywhere; beautifully
gowned ladies and men in striking uniforms, or the courtly dress of
the period, filled the rooms.
Ben was warmly greeted by Lieutenant Claflin, Betsy’s brother, by
that young lady herself and by their father.
“Hah, you young rascal,” quavered the old gentleman, as he clung to
Ben’s hand. “I’ve just been talking to General Greene, and I begin to
find out about you. Why have you not told me of your reputation as
a fire-eater, sir; why have I not heard before of these exploits of
yourself and your friends?”
Ben laughed.
“Oh, General Greene likes his little joke, sir,” remonstrated he. “He
loves to make much of these little matters of experience.”
“Ah, you rogue, you can’t deceive me. You are a hero, sir, that’s
what you are. And not only General Greene tells me so, but others
as well.”
Here Miss Betsy and some other young ladies took Ben in charge
and stationing themselves in an excellent place for observation,
began to point out all the noted figures of the day, who were as yet
unknown to the camp. A handsome, rather reckless-looking man of
middle size and carrying himself with a swaggering, dragoon-like air,
attracted the attention of the lad in a very few moments.
“And who is that?” he inquired.
“It’s Colonel Conway,” replied one of the girls. “He was born in
Ireland, but has lived most of his life in France.”
“A very gallant and capable officer, I have heard,” remarked another.
“He may be all you say, but I don’t care for him,” spoke a third.
“There is something about him which is repelling.”
“Some of the members of Congress do not find him so,” said Betsy
Claflin, wisely. “He has only been in the country a short time, but
already there is quite a movement in his favor. I have heard it said
that there are some who think of raising him at once to an important
command.”
The young lady who had first spoken now turned a cautious look
about to note if any one were paying attention whom she did not
take into her confidence. Her voice was very low and her manner
profoundly secret as she said:
“Pray don’t breathe a word of this to a living soul, for I had it
privately and in strict confidence. Congress was to make Colonel
Conway a brigadier, but General Washington interfered, and said
that he thought him an unsafe man and scarcely to be trusted with
an important command.”
There was an astonished buzz at this, and then an outbreak of low-
voiced chatter. During this Ben was observing Conway; he, too, felt
repelled by the man’s swaggering, arrogant manner, though he had
not yet overheard a word he said. Suddenly, as he watched he saw a
tall man with powerful features approach the Irish-Frenchman; they
greeted each other eagerly, and as they did so Ben watched the tall
man with eyes full of interested recognition. After a moment or two
of watching he turned to Betsy.
“And who is that, so closely engaged with Colonel Conway?”
Betsy glanced at the person indicated.
“That is a gentleman from the South,” she said. “Savannah, I think,
is his town; and he has been attracted by the Congress and other
things, perhaps, in the city most of the winter. He is a great friend of
Samuel Livingstone, the merchant. They have known each other a
great while, or at least I think I’ve heard it so said. His name is
Tobias Hawkins.”
Ben regarded Tobias Hawkins for a moment more.
“Master Samuel Livingstone vouched for the gentleman, eh?” he
said, musingly.
Betsy looked at him in surprise.
“Why, yes,” she said. “And why not, seeing that they are such old
friends?”
“Ah, why not, indeed?” said Ben.
For a long time he sat with moody face; this was unusual for him,
for cheerfulness was his leading characteristic. The girls strove to
arouse him, but he would emerge from his abstraction only for a
moment at a time; the next would see him with folded arms staring
at the floor, or regarding Master Hawkins with fixed and speculative
eye.
Later in the evening he was chatting with Lieutenant Claflin, and
some others, when he noted a tall, fine-looking officer go by; and at
his side was Tobias Hawkins, smiling and genial, and apparently
relating some witticism—for the officer, as they passed, laughed
gaily.
“Gates is a handsome fellow,” said a civilian youth to one of the
young officers in the group. “And a good-humored one, I think.”
The young officer grimaced.
“I have served under him,” he said. “And I found him good-humored
if one played the jester to him. With the sun shining, give me Gates;
but with an overcast sky, I would prefer some more stable person.”
The young civilian looked astonished.
“Why,” said he, “is it possible that General Gates is not thought
highly of in the army? I take from your tone that you meant that,” in
hurried explanation.
“I did mean it,” smiled the youthful officer. “Gates has the military
knowledge—no one can deny that—but,” and the speaker tapped his
forehead with one finger, “it is here that he is deficient. He has not
the judgment, the depth, that ability to apply his knowledge which
makes the general.”
Lieutenant Claflin laughed, as did some others.
“Oh, come now, Hungerford,” said Claflin, “don’t be so severe upon
the general. Remember, he has been engaged in military service of
one sort or another for only thirty years, while you have worn a
sword for as long a time as six months.”
Again there was a laugh, and young Hungerford flushed.
“As for that,” said he, frankly enough, “I am not passing personal
judgment upon General Gates. I am merely stating what I know are
the opinions of men of experience. Why, General Washington himself
holds him in no high esteem, for some time ago when Gates asked
for a brigade, he refused to give it to him, there being others in
whom he had more faith.”
Ben’s eyes followed the handsome figure of Gates and that of Tobias
Hawkins; and once more the moody look came into his face.
“What can it mean?” he asked himself. “What is this man’s purpose?
He has pushed himself into the good graces of a rather simple-
minded merchant, and so has gained entry into the society of the
city. And what I noted on the first night at this very inn has since
been verified. For some reason he then was eager to know the
names of those opposed to General Washington, and since then all
those with whom I have seen him upon intimate terms are of that
stripe. First, there was Mifflin, who is noted for his dislike of the
general, then there is Conway, and now Gates.” The boy looked
down the long room at the two men and his thoughts went on: “He
has some reason. His desire must be to——”
Here he was interrupted by a general movement toward the room
where the dinner was to be served, and he found himself paired with
a dark-haired, bright-eyed girl whose English pronunciation proved
her to be of French birth. At the table this young lady proved to be a
most diverting companion. She knew every one and the history of
every one.
“I am at great pains to acquire information,” she smilingly told Ben.
“For, you see, I am keeping a journal in which I write down every
scrap of intelligence. In years to come it will be a highly-prized book;
even scholars will go to it when they desire a true picture of these
days.”
Listening to her chatter pleased Ben Cooper, and soon all thought of
Tobias Hawkins had passed out of his mind. Almost across the table
from them were a number of foreigners who had come to America in
search of military preferment. One of these was manifestly of
German extraction, a grave-faced man of middle age; another was a
handsome lad of about Ben’s own years. The latter was laughing
gaily with those near him and talking in English, but with a decided
French accent.
“That,” said Ben, “is a countryman of yours.”
His companion shrugged her shoulders, helplessly.
“One sees so many countrymen of mine these days, that it might be
thought Congress intended to officer the American army from
France,” she said. “And some of them—oh, what preposterous
fellows they are! So much pretense, so much vainglory. It is really
ridiculous.”
Ben had his eyes upon the engaging countenance of the French lad
across the table.
“That one, at least,” said he, “has none of those things.”
The girl nodded her agreement of this.
“He is very well, indeed,” she said. “I have met him, and my father
has told me his family history.”
Just then the young Frenchman burst out in his imperfect English:
“But such a wonderful country—so beautiful a land. It is well to fight
that such a country should be free. I am lost in admiration of it.”
“But, sir,” laughingly protested one of the ladies, “you have been
here a very short time, and you can have seen but little of it.”
“Ah, madame, there you are mistaken,” cried the lad, delightedly. “I
have seen nine hundred miles of it, my friends and I. Nine hundred
miles did we ride from Georgetown in South Carolina, where my ship
reached port. Nine hundred miles through a glorious country; and
the sight of it day after day, madame, made me more determined
than ever to join your army and help fight for it.”
“You say you know his name and history,” said Ben Cooper to the girl
at his side. “Who and what is he?”
“He was born in Cavanac, Auvergne, France,” said the young lady
with affected solemnity, “and he is now just nineteen years of age.
His name is——” she paused and affected great concern. “Do you
care to hear his full name?” she asked.
“Full and complete, so that I may know the worst at once,” smiled
Ben.
“Very well, then. It is Marie Jean Paul Roch Yves Gilbert Motier,
Marquis de Lafayette. He is enormously rich, has been a captain of
dragoons, and has made very great sacrifices at home in France that
he might come here and offer his sword to Congress.”
Ben regarded the young Frenchman with increased attention.
“Why,” said the American boy, “here is a generous and unselfish
spirit, indeed. To leave a great fortune, honors, no doubt——”
“All that the French king could confer upon one so young,” put in the
girl. “But no, he would have none of it. He had heard of the struggle
here, and asked Mr. Franklin at Paris for service. After the defeat of
Long Island the Americans had no credit in Europe; no one believed
in them, it seems, and so Mr. Franklin could secure no ship to carry
the French boy and his friends.
“‘We are sorry,’ said Franklin, ‘but you will have to await our better
fortune.’
“But not so! He could not wait. He bought a ship of his own and set
sail; and here he is, offering himself to Congress, to fight the
British.”
After dinner the young Marquis and Ben Cooper were presented to
each other, and when the French lad learned that Ben was upon
active service with Washington he was delighted.
“You cannot understand,” said he, “how we admire this general of
yours in Europe. The great Frederic of Prussia says that his strategy
stamps him as the world’s greatest soldier.”
The two were still deeply engaged, Ben relating some camp
anecdotes of the commander-in-chief, to Lafayette’s vast admiration,
when there was a stir, a rustle, a hum of voices, a crowding to the
front; but neither of the young men paid any attention; until, after a
little, the voice of old Mr. Claflin said:
“What, Marquis, I thought you were wild to meet our general. And
here he is and you have not even so much as a look for him.”
Turning, his face alight, the next moment Lafayette was face to face
with Washington for the first time, and listening to the calm, steady
voice which he was afterward to hear so often in the press of battle.
LAFAYETTE WAS FACE TO FACE
WITH WASHINGTON
Soon there was quite a throng about the two. The fame of the
young nobleman, who so loved freedom that he would give up all
that most men covet in order that he might cross a sea and strike a
blow for a stranger race, was all about the city. For the most part the
foreigners who offered themselves were professional soldiers who
sought the power and emoluments of rank. But here was one wholly
different; he already had rank and fortune; he desired only to serve.
The admiration of Washington was plainly visible; he applauded this
youth for his unselfishness; he loved him from the first for his high
heart and noble generosity.
But on the outskirts of the throng there was a little group in which
no sympathy for the meeting seemed to find a place. In this party
Ben saw the cold face of General Mifflin, the vain, handsome
countenance of General Gates, and the reckless, selfish one of
Colonel Conway. These three gazed at the little scene before them
with eyes totally unresponsive; they whispered, exchanged looks of
unbelief and smiles which scarcely concealed the sneers behind
them. These things alone aroused Ben Cooper’s resentment; but
there was a chill at his heart, a feeling of vague fear, as he saw the
satisfaction upon the face of the man in the rear of the three. And
that man was Master Tobias Hawkins.
CHAPTER X
SHOWS HOW THE FIGHT AT BRANDYWINE
WAS
LOST, AND HOW BEN BORE THE TIDINGS TO
PHILADELPHIA

Having made up his mind that nothing could be gained by seeking to


draw Washington into a trap, General Howe finally decided upon a
plan and embarked his troops. What he would do was a matter for
speculation in the American army; every one wondered where the
next blow would fall. Thinking that Philadelphia must be the point
aimed at, Washington once more crossed the Delaware and took up
a position at Germantown. While here the tidings came that the
British troop ships had entered Chesapeake Bay, and that Howe’s
army would disembark at the head of the Elk River.
At this news the Tories in Philadelphia became overbold, and
thinking to put them down by a display of power, Washington on the
way southward marched his array through Front and along Chestnut
Streets with bands playing and colors flying. There were some
twelve thousand of them, while the British, whom they were
advancing to check, numbered almost twenty thousand, with
powerful artillery.
The Americans marched to Wilmington, and there entered camp
upon some heights near to the Christiana and the Brandywine.
Heavy parties were sent forward to come in touch with the enemy
and harass his advance as much as possible. Howe landed his force
at a point seventy miles from Philadelphia, and almost at once took
up his line of march. The militia and other parties sent out by
Washington rendered this progress much slower than it would
otherwise have been, and in this way the American commander was
given an opportunity to reconnoiter the roads and passes and fords.
“It looks,” said George Prentiss to Ben, “as though the general had
made up his mind to risk a battle in the open.”
“He must, if he is to fight at all, I think,” said Ben. “And that he must
fight is settled. Philadelphia, the city where Congress meets, must
not be allowed to fall without a blow.”
“Right,” spoke Nat Brewster. “That would never do, as I look at it.
Everything must be risked at this point; to desert the city, now that
the enemy are approaching it, would be to lose its confidence
forever.”
Talk of this sort ran through the American force, showing that the
rank and file understood the position in which their officers stood.
And the position was a most critical one. The great bulk of the army
was made up of raw men, the militia of New Jersey, Pennsylvania
and Delaware; and in no way was the American force to be
compared to the British—neither in number, equipment nor
discipline.
At White Clay Creek, General Maxwell’s sharpshooters encountered
the British vanguard, and a spirited fight took place, the
sharpshooters falling back, but the invaders meeting with much the
greater loss. At first Washington selected a position on the east of
Red Clay Creek, on the Philadelphia road; but he discovered the
intention of Sir William Howe to pass the Brandywine, gain the
heights to the north of the stream and so cut him off from
Philadelphia; the American army was put in motion during the night
and took possession of this point.
There were several crossings of the Brandywine and the best of
them was in direct line with the enemy’s advance. This was called
Chadd’s Ford, and here Washington stationed the main body of his
army under Wayne, Weedon and Muhlenberg. Maxwell’s riflemen
were also placed at this point, and Wayne’s and Proctor’s artillery
were placed upon a hill commanding the ford. The right wing was in
the care of General Sullivan, Sterling and Stephen, while the left,
mainly militia, was commanded by General Armstrong.
What seemed to be the main body of the enemy began an advance
on Chadd’s Ford early on the morning of September 11th.
Washington rode along the ranks cheering his men and being
cheered in return. The reports of the rifles of Maxwell’s men soon
began to be heard across the Brandywine; after a long time spent in
skirmishing, the sharpshooters themselves were driven across the
stream. The enemy did not attempt to follow, but their artillery
opened, and the American guns answered promptly.
While this was going on a rider from General Sullivan’s command
dashed up to headquarters bearing the news that a heavy body of
troops under Howe was pushing along the Lancaster road with the
intent to cross at one of the upper fords and turn the American right
flank. Instantly a party of riders were sent to ascertain the truth of
this; then the Americans determined to cross the creek and attack
those before them, word being sent to both wings to do likewise.
But just as the movement was begun, word came by a militia major
that there was no enemy in the quarter Howe was reported to be in,
and instantly Washington halted the troops once more. Horsemen
were scurrying backward and forward—all was in suspense. Finally a
resident of the section, Squire Cheyney, came galloping up,
breathless, and with horse covered with foam; he had come upon
the main body of the British as they were hurrying along on the east
side of the stream; they had fired upon him, but he had succeeded
in reaching the American lines unhurt.
“You must move, General Washington,” he cried, “or you will be
surrounded.”
The horsemen, sent out earlier, now returned, confirming this. The
British main body, under Cornwallis, was sweeping down upon the
right wing. Without hesitation, Washington’s orders were given.
Sullivan was to attack the invaders, Sterling’s and Stephen’s brigades
were to support him. Wayne was to hold Chadd’s Ford and see to it
that the German Knyphausen did not cross, while General Greene
was to hold his command ready to dash in wherever needed.
Sullivan followed his orders, but the time which had elapsed
between the warning and the orders reaching him enabled
Cornwallis to select his own ground. Taken at a complete
disadvantage, the Americans broke on each wing; the center stood
firm, but receiving the concentrated fire of the enemy, it, too, gave
way. The young Lafayette, who had begged permission to go where
the fight would be thickest, seeing that the pursuing British became
entangled in the wood, leaped from his horse and made a gallant
attempt to rally the broken division of Sullivan.
“He proves true under the guns of the enemy,” spoke Nat Brewster,
admiringly.
Ben Cooper paused and wiped away the perspiration which
streamed from his face.
“I knew he would, the first time I——” Suddenly he stopped and
uttered a cry; then both he and Nat drove spurs to their horses and
raced forward.
As Lafayette strove with the disorganized rabble of fleeing militia, a
mass of British suddenly appeared, emerging from the wood; their
pieces sent a volley into the fugitives, and at the discharge Lafayette
fell. Side by side Ben Cooper and the stalwart Nat Brewster swept
forward; as they neared the young Frenchman they opened a trifle,
then bending simultaneously, their horses slowing, they lifted him
from the ground, swung him across Nat’s horse—turned in the very
teeth of the oncoming British, and sped away.
Washington came up with fresh troops, and the Americans made a
stand upon a hill near Dilworth; but again they were driven back
with much loss.
Knyphausen, hearing the heavy firing, which was his signal to move
in earnest, made a rush to cross Chadd’s Ford. Wayne’s and Proctor’s
artillery began to sound and Maxwell’s riflemen picked off the
advance. General Greene was also preparing to oppose the
oncoming German, when Ezra Prentiss rode up with orders from the
commander-in-chief that he come to the aid of the right wing, which
was in desperate peril.
Without the waste of a moment the division of Greene was put into
motion and never was there more rapid marching. It is said that the
brigade covered the distance of five miles in less than fifty minutes.
But, for all his gallant effort, he was too late to prevent defeat.
However, he was well in time to cover the retreat; with his field
pieces well planted he kept up a steady fire; again and again his
ranks opened to allow the blocks of fugitives to pass to the rear. It
was a spot selected by Washington the day before as an excellent
one for a stand should the army be driven from its first position, and
right well did it prove his judgment.
Cornwallis, flushed with success, came on with the exultation of a
victor; he had seen the Americans running away, and thought in the
pursuit to deal them a fatal blow. But Greene with his guns, and
Muhlenberg’s and Weedon’s brigades met them fairly and drove
them back repeatedly. Finally the British became so exhausted that
Greene saw his opportunity and drew off his men in an orderly
manner; and so threatening were his guns, so desperate the aspect
of his grim ranks that the enemy did not make any effort at pursuit.
Wayne also had kept his opponents back at the ford; and he, too,
now drew off his force in such perfect order that Knyphausen did not
dare to follow.
With the Chester road so well covered as to prevent any calamity,
Washington, after a consultation with his generals, wrote a dispatch
giving a full account of the day’s fortunes and misfortunes, knowing
well that a horde of panic-stricken runaways would soon burst into
Philadelphia and spread the news of utter rout.
“Ride with all speed and deliver this to Mr. Hancock,” said the
general, upon handing the dispatch to Ben Cooper. “And do what
you can to stem the tide of false reports that will be going about.”
Then as Ben saluted and gathered up his reins, the commander-in-
chief added anxiously, to General Greene, “I trust no disorder arises
in the city; there are, as you know, many who would willingly take
advantage of so rich an opportunity.”
As Ben sped along the Chester road, his horse pushed its way, in
places, through dense masses of retreating soldiers; the broken
fragments of the army, also field pieces and baggage wagons were
flowing along in one disorganized stream, all making for
Philadelphia. At Chester, some dozen miles north of the scene of
battle, was a good sized stream which the fugitives would have to
cross to reach the city. Here young Lafayette placed a strong guard
at the bridge and refused to permit any one to cross unless properly
armed with an order from some one in authority.
With his leg swathed in bandages showing where the bullet had
struck him, the youthful Frenchman sat his horse with much
difficulty. However, sit him he did, and gave his orders like one born
to the work, never betraying a sign of pain. He recognized Ben at
once as he came up and replied to his salute, and inquired anxiously
as to the complexion of things at Dilworth.
“General Greene held them until the danger was past,” replied Ben,
cheerfully. “And it looks now as though the situation were well in
hand.”
“Ah, yes,” Lafayette said. “With us there was fortune at any rate. We
lost the battle, but,” and he gestured eloquently, “we are saved from
utter ruin; and another day we can fight again.”
Ben pushed on at top speed; all along the road he found wagons
loaded with household goods and such like, with excited men, white-
faced women and crying children trudging at their sides. The news
of the defeat had reached them, also the report that Washington’s
army had been cut to pieces and was flying in complete rout before
the British. The lad did his best to steady the men by crying out to
them that Washington was holding Howe in check.
As he passed into the city he found much the same state of things;
all day the citizens had gathered in the streets and public squares,
listening to the roar of the cannon which came plainly to their ears;
and now the fleeing families grew more numerous; terror seemed to
be in every face. The throngs recognized Ben in a moment as being
one from the battle-field; they closed around him demanding tidings.
“What news?” called one.
“How goes the fight?” demanded another.
“What’s left of the army?” questioned a third.
“How soon will the British be here?” cried another.
Ben waved a hand to them—the hand which held his dispatches.
“Make way,” he cried out, repeatedly. “Make way for the messenger
to Congress.”
“The battle! the battle!” chorused the populace. “What news from
the army?”
“The army was driven back——” A groan interrupted the boy. He
continued: “But the British were repulsed at last. The army is safe!”
The more hardy spirits found comfort in this last; but the greater
part lost none of their fear; the steady stream of fleeing families still
passed along the streets; men rushed hither and thither, preparing
to depart, women sobbed and gathered their children about them.
“To the mountains,” was the cry. “To the mountains!”
Ben leaped from his horse at the State House door; but upon inquiry
he learned that Congress was not sitting as he had expected it to be
in such a crisis. It had held a session that evening and decided to
quit the city; the next meeting of the body was to be held at
Lancaster.
“But,” said the custodian, “a number of the members are now at
Clark’s Inn, just across the way; and I feel sure that you’ll find Mr.
Hancock there, also.”
Clark’s Inn was a quaint and ancient place, almost as old as the city
itself; the doors stood wide and the light streamed out upon the
stone-paved walk. Within, all was hubbub; the day’s misfortunes
were, of course, the chief topic, but the decision of Congress to quit
the city was almost as much discussed.
“What do I call it, sir?” were the first words that come to Ben’s ears
as he entered the inn. “What do I call it, do you say? Why, I call it
cowardice, sir, rank cowardice.”
The speaker was the stout Master Samuel Livingstone, whom Ben
had met with several times before. His face was mottled with
excitement, and one fat hand beat the table before him.
“Not cowardice, perhaps,” said the person to whom he addressed
himself. “Not cowardice, exactly, but rather unseemly haste.”
“It is cowardice, sir!” maintained Master Livingstone. “It is just that,
and nothing less! Was it not Congress who brought us all to the
point of resistance to the king? Was it not, I ask of you? And now
that we have resisted to the extent of all we have, what does
Congress do?” He paused, and his great face glowered at the man to
whom he was speaking. “It deserts us! No sooner does it hear of the
enemy’s approach to the city than it deserts us. The moment that
the slightest chance of danger to itself appears, it flies.”
Here the other man held up a warning finger; bending across the
table he said something in a low tone. Master Livingstone grew a
little paler in color; his manner took on a trace of anxiety.
“Hah!” said he, as his eyes went about the room, alarmed. “Yes, yes,
you are right. Perhaps I had best not go too far. I did not know,” in a
still lower tone, “that our friends voted for the removal to Lancaster.”
In a quiet corner, Ben found John Hancock and some friends soberly
talking over the momentous happenings of the day. The elegant
Hancock received the boy with the rather distant formality for which
he was known; and the dispatches were read at once.
“Somewhat too late,” said he, coldly, after reading the hasty lines to
his friends. “This matter of there being no immediate danger will
have to be acted upon at Lancaster.”
There was a slight laugh at this, for the remark was evidently
intended as a witticism.
“At a little distance inland,” spoke one of the party, also a member of
the Congress, “we can be assured of safety. For even our present
commanders will scarcely allow the enemy to penetrate that far.”
“Washington,” said Mr. Hancock, “has not failed altogether. He has
given us victories. Remember, sir, with the means at his hand he
cannot win all the time. It is too much to require of any general.”
“But action is not too much to require of a general; it is not too
much to ask the commander of an army that he have some
enterprise; that he take the initiative occasionally, that he do not
always wait until the enemy advances upon him before he makes a
show of fighting.”
“Right! Right!” came a number of voices. “Quite right!”
But another member, and apparently a supporter of Washington,
here spoke out.
“I think,” said he, “you have not properly considered what Mr.
Hancock meant when he mentioned ‘the means at his hand.’” The
speaker tapped the table edge with the tip of one finger and
proceeded: “When one considers the slender supply of soldiers
which present themselves for service, one might wonder very
properly where an army sufficiently powerful to cope with England is
coming from. And even the small force which our general gathers
only remains with him a short time. The term of enlistment is so
short that scarcely has a regiment reached a fair state of discipline
than it disbands—and in this constant recruiting and training, the
personnel of the army never reaches any but a most indifferent
state. And, then, the money with which the force is to be
maintained!” here the member looked about him and smiled. “What
must keep Washington going for weeks would not cover the
requirements of Howe for days. The supplies are seldom of sufficient
quantity to fill the needs of our soldiers; the men go barefoot in the
ranks; the able men lack the arms to fight with, and the sick men
have not the medicine to make them well.”
At this there arose a chorus of approval and protest; the gathered
members and their friends entered into the case with spirit and heat,
and in the clamor that followed Ben heard little more. Having had
nothing to eat since early morning, the lad, for the first time, began
to feel a trifle faint; until this the excitement had sustained him, but
the need of food was now strongly brought to his mind. So seating
himself in a quiet nook near to a window at the front of the house
he ordered a dish of eggs with bacon and well browned bread and
other comforting things. The window was raised a few inches.
When these were placed before him, he fell to with relish and will,
paying little attention to the high talk going on all about him.
Outside the inn door were several benches where patrons of the
place were accustomed to sit in pleasant weather, and as Ben gazed
idly out through the window at his elbow he found himself looking at
the back of one of these, which was so placed; and over the top of it
he saw the crown of a hat.
“Some sensible person who quietly takes the air in spite of the cold
weather,” said Ben. “All this clatter and complaining is not worth
listening to, he thinks, and so he will have none of it.”
He had about reached this conclusion, when he saw a tall figure turn
in from the street toward the inn door. At a glance the lad
recognized Tobias Hawkins; the next moment the man upon the
bench had arisen to greet the newcomer, and he, in turn, Ben knew,
even in the indifferent light and though his back was turned, as the
man with the yellow smile.
CHAPTER XI
TELLS HOW BEN COOPER LISTENED TO SOME
ASTONISHING REVELATIONS

From the manner of the men, it was evident that the coming of
Tobias Hawkins was no surprise to his friend. Indeed, the latter had
been, it was evident, patiently awaiting him; and now the eagerness
in his manner showed plainly that he attached some importance to
the arrival.
“I had about given up all hope of you,” said the man with the yellow
smile, his first words showing the truth of the lad’s discernment.
“I said I would reach here as soon after nine o’clock as I could. To
be sure, it is somewhat after that; but I could not finish my business
earlier.”
“The hour at which it is finished,” said the other, “does not greatly
matter. The question is, how did you succeed?”
Tobias Hawkins laughed and in the sound of that laugh Ben caught
something like triumph.
“Success,” said the man, “is so easily won, that there is no credit in
it. But let us go inside where we can talk quietly.”
“It would be much better if we remained where we are,” said the
other, looking about. “The inn is filled with madmen, I think. They
can do nothing but rave over the defeat of Washington and the flight
of Congress.”
Hawkins, after a cautious glance about, seated himself upon the
bench. A small cedar in a tub concealed the window at which Ben
sat; the boy could see only the crowns of the two hats over the high
back of the bench, but the delighted sound that came from Hawkins
told him that the man was chuckling.
“Washington’s defeat,” repeated Hawkins; “ah, what a relief that
was! It altered things all about me. Trenton and Princeton and the
affairs in the Jerseys had set me a task that I sometimes despaired
of, Sugden; but this one defeat brought all the complainings to the
top again. The victories were forgotten; the commander had lost a
battle, therefore the commander was incompetent.”
“A rare good general, this Washington, I think,” said Sugden. “A
careful fighter and one that will last long—if they allow him?”
There was a laugh with this last, a mocking sort of laugh which
indicated the speaker’s disbelief in the possibility.
“With the goodness or the badness of Mr. Washington as an officer,
we personally have nothing to do,” said Hawkins. “We are paid to
excite disbelief in him; our duty is to have him supplanted by a
weaker man, so let us be about that, and bother with nothing else.”
Ben felt his heart throb heavily at this, and the blood beat about his
temples and roared in his ears. Here at last was the thing which he
had thought for so long, put plainly into words. There was a
movement on foot to displace Washington as head of the army;
fearing that its forces would not be equal to the task of subduing the
aroused colonies, the British government had set about undermining
the one man whose genius they feared in the field.
“A conspiracy,” breathed Ben. “A conspiracy conducted by this man
Hawkins!”
Now better than ever did the lad understand the actions of Tobias
Hawkins. As he thought over all the man’s doings and sayings he
fancied that they all centered in the one purpose.
“On New Year’s Eve, when I first saw him, he was but newly come
to Philadelphia to begin his plotting; and that faultfinding old fellow,
Livingstone, was just the sort of man he needed to enable him to

You might also like