SlideShare a Scribd company logo
Jquery Cookbook Solutions Examples For Jquery
Developers Lindley download
https://ebookbell.com/product/jquery-cookbook-solutions-examples-
for-jquery-developers-lindley-22034660
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Jquery Cookbook Cody Lindley Simon St Laurent
https://ebookbell.com/product/jquery-cookbook-cody-lindley-simon-st-
laurent-2466982
Php Jquery Cookbook Vijay Joshi
https://ebookbell.com/product/php-jquery-cookbook-vijay-joshi-2531248
Aspnet Jquery Cookbook Sonal Aneel Allana
https://ebookbell.com/product/aspnet-jquery-cookbook-sonal-aneel-
allana-2243906
Aspnet Jquery Cookbook 2nd Edition Over 60 Recipes For Writing Client
Script In Aspnet 46 Applications Using Jquery Sonal Aneel Allana
https://ebookbell.com/product/aspnet-jquery-cookbook-2nd-edition-
over-60-recipes-for-writing-client-script-in-aspnet-46-applications-
using-jquery-sonal-aneel-allana-5476280
Jquery Mobile Cookbook Chetan K Jain
https://ebookbell.com/product/jquery-mobile-cookbook-chetan-k-
jain-2624350
Jquery Ui Cookbook Adam Boduch
https://ebookbell.com/product/jquery-ui-cookbook-adam-boduch-4430518
Jquery 20 Development Cookbook 1st Edition Leon Revill
https://ebookbell.com/product/jquery-20-development-cookbook-1st-
edition-leon-revill-23866524
Jquery For Designers Meap Remy Sharp
https://ebookbell.com/product/jquery-for-designers-meap-remy-
sharp-46601000
Jquery Ui In Action 1st Edition Tj Vantoll
https://ebookbell.com/product/jquery-ui-in-action-1st-edition-tj-
vantoll-46635972
Jquery Cookbook Solutions Examples For Jquery Developers Lindley
Jquery Cookbook Solutions Examples For Jquery Developers Lindley
Jquery Cookbook Solutions Examples For Jquery Developers Lindley
jQuery Cookbook
Jquery Cookbook Solutions Examples For Jquery Developers Lindley
jQuery Cookbook
jQuery Community Experts
Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
jQuery Cookbook
by jQuery Community Experts
Copyright © 2010 Cody Lindley. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://my.safaribooksonline.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com.
Editor: Simon St.Laurent
Production Editor: Sarah Schneider
Copyeditor: Kim Wimpsett
Proofreader: Andrea Fox
Production Services: Molly Sharp
Indexer: Fred Brown
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Robert Romano
Printing History:
November 2009: First Edition.
O’Reilly and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. jQuery Cookbook, the
image of an ermine, and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
TM
This book uses RepKover, a durable and flexible lay-flat binding.
ISBN: 978-0-596-15977-1
[S]
1257774409
Table of Contents
Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
1. jQuery Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Including the jQuery Library Code in an HTML Page 9
1.2 Executing jQuery/JavaScript Coded After the DOM Has Loaded
but Before Complete Page Load 10
1.3 Selecting DOM Elements Using Selectors and the jQuery Function 13
1.4 Selecting DOM Elements Within a Specified Context 15
1.5 Filtering a Wrapper Set of DOM Elements 16
1.6 Finding Descendant Elements Within the Currently Selected
Wrapper Set 18
1.7 Returning to the Prior Selection Before a Destructive Change 19
1.8 Including the Previous Selection with the Current Selection 20
1.9 Traversing the DOM Based on Your Current Context to Acquire a
New Set of DOM Elements 21
1.10 Creating, Operating on, and Inserting DOM Elements 23
1.11 Removing DOM Elements 24
1.12 Replacing DOM Elements 26
1.13 Cloning DOM Elements 27
1.14 Getting, Setting, and Removing DOM Element Attributes 29
1.15 Getting and Setting HTML Content 30
1.16 Getting and Setting Text Content 31
1.17 Using the $ Alias Without Creating Global Conflicts 32
2. Selecting Elements with jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.1 Selecting Child Elements Only 36
2.2 Selecting Specific Siblings 37
v
2.3 Selecting Elements by Index Order 39
2.4 Selecting Elements That Are Currently Animating 41
2.5 Selecting Elements Based on What They Contain 42
2.6 Selecting Elements by What They Don’t Match 43
2.7 Selecting Elements Based on Their Visibility 43
2.8 Selecting Elements Based on Attributes 44
2.9 Selecting Form Elements by Type 46
2.10 Selecting an Element with Specific Characteristics 47
2.11 Using the Context Parameter 48
2.12 Creating a Custom Filter Selector 50
3. Beyond the Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3.1 Looping Through a Set of Selected Results 53
3.2 Reducing the Selection Set to a Specified Item 56
3.3 Convert a Selected jQuery Object into a Raw DOM Object 59
3.4 Getting the Index of an Item in a Selection 62
3.5 Making a Unique Array of Values from an Existing Array 64
3.6 Performing an Action on a Subset of the Selected Set 67
3.7 Configuring jQuery Not to Conflict with Other Libraries 69
3.8 Adding Functionality with Plugins 72
3.9 Determining the Exact Query That Was Used 74
4. jQuery Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
4.1 Detecting Features with jQuery.support 77
4.2 Iterating Over Arrays and Objects with jQuery.each 79
4.3 Filtering Arrays with jQuery.grep 80
4.4 Iterating and Modifying Array Entries with jQuery.map 81
4.5 Combining Two Arrays with jQuery.merge 81
4.6 Filtering Out Duplicate Array Entries with jQuery.unique 82
4.7 Testing Callback Functions with jQuery.isFunction 82
4.8 Removing Whitespace from Strings or Form Values with
jQuery.trim 83
4.9 Attaching Objects and Data to DOM with jQuery.data 84
4.10 Extending Objects with jQuery.extend 85
5. Faster, Simpler, More Fun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.1 That’s Not jQuery, It’s JavaScript! 87
5.2 What’s Wrong with $(this)? 88
5.3 Removing Redundant Repetition 91
5.4 Formatting Your jQuery Chains 92
5.5 Borrowing Code from Other Libraries 94
5.6 Writing a Custom Iterator 96
5.7 Toggling an Attribute 99
vi | Table of Contents
5.8 Finding the Bottlenecks 101
5.9 Caching Your jQuery Objects 105
5.10 Writing Faster Selectors 107
5.11 Loading Tables Faster 109
5.12 Coding Bare-Metal Loops 112
5.13 Reducing Name Lookups 115
5.14 Updating the DOM Faster with .innerHTML 117
5.15 Debugging? Break Those Chains 118
5.16 Is It a jQuery Bug? 120
5.17 Tracing into jQuery 121
5.18 Making Fewer Server Requests 123
5.19 Writing Unobtrusive JavaScript 126
5.20 Using jQuery for Progressive Enhancement 128
5.21 Making Your Pages Accessible 130
6. Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
6.1 Finding the Dimensions of the Window and Document 135
6.2 Finding the Dimensions of an Element 137
6.3 Finding the Offset of an Element 139
6.4 Scrolling an Element into View 141
6.5 Determining Whether an Element Is Within the Viewport 143
6.6 Centering an Element Within the Viewport 146
6.7 Absolutely Positioning an Element at Its Current Position 147
6.8 Positioning an Element Relative to Another Element 147
6.9 Switching Stylesheets Based on Browser Width 148
7. Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
7.1 Sliding and Fading Elements in and out of View 153
7.2 Making Elements Visible by Sliding Them Up 156
7.3 Creating a Horizontal Accordion 157
7.4 Simultaneously Sliding and Fading Elements 161
7.5 Applying Sequential Effects 162
7.6 Determining Whether Elements Are Currently Being Animated 164
7.7 Stopping and Resetting Animations 165
7.8 Using Custom Easing Methods for Effects 166
7.9 Disabling All Effects 168
7.10 Using jQuery UI for Advanced Effects 168
8. Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
8.1 Attaching a Handler to Many Events 172
8.2 Reusing a Handler Function with Different Data 173
8.3 Removing a Whole Set of Event Handlers 175
8.4 Triggering Specific Event Handlers 176
Table of Contents | vii
8.5 Passing Dynamic Data to Event Handlers 177
8.6 Accessing an Element ASAP (Before document.ready) 179
8.7 Stopping the Handler Execution Loop 182
8.8 Getting the Correct Element When Using event.target 184
8.9 Avoid Multiple hover() Animations in Parallel 185
8.10 Making Event Handlers Work for Newly Added Elements 187
9. Advanced Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
9.1 Getting jQuery to Work When Loaded Dynamically 191
9.2 Speeding Up Global Event Triggering 192
9.3 Creating Your Own Events 195
9.4 Letting Event Handlers Provide Needed Data 198
9.5 Creating Event-Driven Plugins 201
9.6 Getting Notified When jQuery Methods Are Called 205
9.7 Using Objects’ Methods as Event Listeners 208
10. HTML Form Enhancements from Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
10.1 Focusing a Text Input on Page Load 212
10.2 Disabling and Enabling Form Elements 213
10.3 Selecting Radio Buttons Automatically 216
10.4 (De)selecting All Checkboxes Using Dedicated Links 218
10.5 (De)selecting All Checkboxes Using a Single Toggle 219
10.6 Adding and Removing Select Options 221
10.7 Autotabbing Based on Character Count 222
10.8 Displaying Remaining Character Count 224
10.9 Constraining Text Input to Specific Characters 226
10.10 Submitting a Form Using Ajax 228
10.11 Validating Forms 229
11. HTML Form Enhancements with Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
11.1 Validating Forms 238
11.2 Creating Masked Input Fields 247
11.3 Autocompleting Text Fields 249
11.4 Selecting a Range of Values 250
11.5 Entering a Range-Constrained Value 253
11.6 Uploading Files in the Background 255
11.7 Limiting the Length of Text Inputs 256
11.8 Displaying Labels Above Input Fields 257
11.9 Growing an Input with Its Content 259
11.10 Choosing a Date 260
12. jQuery Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
12.1 Where Do You Find jQuery Plugins? 263
viii | Table of Contents
12.2 When Should You Write a jQuery Plugin? 265
12.3 Writing Your First jQuery Plugin 267
12.4 Passing Options into Your Plugin 268
12.5 Using the $ Shortcut in Your Plugin 270
12.6 Including Private Functions in Your Plugin 272
12.7 Supporting the Metadata Plugin 273
12.8 Adding a Static Function to Your Plugin 275
12.9 Unit Testing Your Plugin with QUnit 277
13. Interface Components from Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
13.1 Creating Custom Tool Tips 280
13.2 Navigating with a File-Tree Expander 285
13.3 Expanding an Accordion 288
13.4 Tabbing Through a Document 293
13.5 Displaying a Simple Modal Window 296
13.6 Building Drop-Down Menus 303
13.7 Cross-Fading Rotating Images 305
13.8 Sliding Panels 310
14. User Interfaces with jQuery UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
14.1 Including the Entire jQuery UI Suite 317
14.2 Including an Individual jQuery UI Plugin or Two 318
14.3 Initializing a jQuery UI Plugin with Default Options 319
14.4 Initializing a jQuery UI Plugin with Custom Options 320
14.5 Creating Your Very Own jQuery UI Plugin Defaults 321
14.6 Getting and Setting jQuery UI Plugin Options 323
14.7 Calling jQuery UI Plugin Methods 323
14.8 Handling jQuery UI Plugin Events 324
14.9 Destroying a jQuery UI Plugin 326
14.10 Creating a jQuery UI Music Player 327
15. jQuery UI Theming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
15.1 Styling jQuery UI Widgets with ThemeRoller 345
15.2 Overriding jQuery UI Layout and Theme Styles 360
15.3 Applying a Theme to Non-jQuery UI Components 370
15.4 Referencing Multiple Themes on a Single Page 379
15.5 Appendix: Additional CSS Resources 388
16. jQuery, Ajax, Data Formats: HTML, XML, JSON, JSONP . . . . . . . . . . . . . . . . . . . . . . . 391
16.1 jQuery and Ajax 391
16.2 Using Ajax on Your Whole Site 394
16.3 Using Simple Ajax with User Feedback 396
16.4 Using Ajax Shortcuts and Data Types 400
Table of Contents | ix
16.5 Using HTML Fragments and jQuery 403
16.6 Converting XML to DOM 404
16.7 Creating JSON 405
16.8 Parsing JSON 406
16.9 Using jQuery and JSONP 407
17. Using jQuery in Large Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
17.1 Using Client-Side Storage 411
17.2 Saving Application State for a Single Session 414
17.3 Saving Application State Between Sessions 416
17.4 Using a JavaScript Template Engine 417
17.5 Queuing Ajax Requests 420
17.6 Dealing with Ajax and the Back Button 422
17.7 Putting JavaScript at the End of a Page 423
18. Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
18.1 Automating Unit Testing 425
18.2 Asserting Results 427
18.3 Testing Synchronous Callbacks 429
18.4 Testing Asynchronous Callbacks 429
18.5 Testing User Actions 431
18.6 Keeping Tests Atomic 432
18.7 Grouping Tests 433
18.8 Selecting Tests to Run 434
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
x | Table of Contents
Foreword
When I first started work on building jQuery, back in 2005, I had a simple goal in mind:
I wanted to be able to write a web application and have it work in all the major
browsers—without further tinkering and bug fixing. It was a couple of months before
I had a set of utilities that were stable enough to achieve that goal for my personal use.
I thought I was relatively done at this point; little did I know that my work was just
beginning.
Since those simple beginnings, jQuery has grown and adapted as new users use the
library for their projects. This has proven to be the most challenging part of developing
a JavaScript library; while it is quite easy to build a library that’ll work for yourself or
a specific application, it becomes incredibly challenging to develop a library that’ll work
in as many environments as possible (old browsers, legacy web pages, and strange
markup abound). Surprisingly, even as jQuery has adapted to handle more use cases,
most of the original API has stayed intact.
One thing I find particularly interesting is to see how developers use jQuery and make
it their own. As someone with a background in computer science, I find it quite sur-
prising that so many designers and nonprogrammers find jQuery to be compelling.
Seeing how they interact with the library has given me a better appreciation of simple
API design. Additionally, seeing many advanced programmers take jQuery and develop
large, complex applications with it has been quite illuminating. The best part of all of
this, though, is the ability to learn from everyone who uses the library.
A side benefit of using jQuery is its extensible plugin structure. When I first developed
jQuery, I was sure to include some simple ways for developers to extend the API that
it provided. This has blossomed into a large and varied community of plugins, encom-
passing a whole ecosystem of applications, developers, and use cases. Much of jQuery’s
growth has been fueled by this community—without it, the library wouldn’t be where
it is today, so I’m glad that there are chapters dedicated to some of the most interesting
plugins and what you can do with them. One of the best ways to expand your precon-
ceived notion of what you can do with jQuery is to learn and use code from the jQuery
plugin community.
xi
This is largely what makes something like a cookbook so interesting: it takes the cool
things that developers have done, and have learned, in their day-to-day coding and
distills it to bite-sized chunks for later consumption. Personally, I find a cookbook to
be one of the best ways to challenge my preconceived notions of a language or library.
I love seeing cases where an API that I thought I knew well is turned around and used
in new and interesting ways. I hope this book is able to serve you well, teaching you
new and interesting ways to use jQuery.
—John Resig
Creator, Lead Developer, jQuery
xii | Foreword
Contributors
Chapter Authors
Jonathan Sharp has been passionate about the Internet and web development since
1996. Over the years that have followed, he has worked for startups and for Fortune
500 corporations. Jonathan founded Out West Media, LLC, in greater Omaha, Ne-
braska, and provides frontend engineering and architecture services with a focus on
custom XHTML, CSS, and jQuery development. Jonathan is a jQuery core team mem-
ber and an author and presenter when not coding. Jonathan is most grateful for his
wife, Erin; daughter, Noel; two dogs, and two horses.
Rob Burns develops interactive web applications at A Mountain Top, LLC. For the
past 12 years he has been exploring website development using a wide range of tools
and technologies. In his spare time, he enjoys natural-language processing and the
wealth of opportunity in open source software projects.
Rebecca Murphey is an independent frontend architecture consultant, crafting cus-
tom frontend solutions that serve as the glue between server and browser. She also
provides training in frontend development, with an emphasis on the jQuery library.
She lives with her partner, two dogs, and two cats in Durham, North Carolina.
Ariel Flesler is a web developer and a video game programmer. He’s been contributing
to jQuery since January 2007 and joined the core team in May 2008. He is 23 years old
and was born in Buenos Aires, Argentina. He’s studying at the National Technological
University (Argentina) and is hoping to become a systems analyst by 2010 and a systems
engineer by 2012. He started working as an ASP.NET(C#) programmer and then
switched to client-side development of XHTML sites and Ajax applications. He’s cur-
rently working at QB9 where he develops AS3-based casual games and MMOs.
Cody Lindley is a Christian, husband, son, father, brother, outdoor enthusiast, and
professional client-side engineer. Since 1997 he has been passionate about HTML, CSS,
JavaScript, Flash, interaction design, interface design, and HCI. He is most well known
in the jQuery community for the creation of ThickBox, a modal/dialog solution. In
2008 he officially joined the jQuery team as an evangelist. His current focus has been
xiii
on client-side optimization techniques as well as speaking and writing about jQuery.
His website is http://www.codylindley.com.
RemySharp is a developer, author, speaker, and blogger. Remy started his professional
web development career in 1999 as the sole developer for a finance website and, as
such, was exposed to all aspects of running the website during, and long after, the
dotcom boom. Today he runs his own development company called Left Logic in
Brighton, UK, writing and coding JavaScript, jQuery, HTML 5, CSS, PHP, Perl, and
anything else he can get his hands on.
Mike Hostetler is an inventor, entrepreneur, programmer, and proud father. Having
worked with web technologies since the mid-1990s, Mike has had extensive experience
developing web applications with PHP and JavaScript. Currently, Mike works at the
helm of A Mountain Top, LLC, a web technology consulting firm in Denver, Colorado.
Heavily involved in open source, Mike is a member of the jQuery core team, leads the
QCubed PHP5 Framework project, and participates in the Drupal project. When not
in front of a computer, Mike enjoys hiking, fly fishing, snowboarding, and spending
time with his family.
RalphWhitbeck is a graduate of the Rochester Institute of Technology and is currently
a senior developer for BrandLogic Corporation in Rochester, New York. His respon-
sibilities at BrandLogic include interface design, usability testing, and web and appli-
cation development. Ralph is able to program complex web application systems in
ASP.NET, C#, and SQL Server and also uses client-side technologies such as XHTML,
CSS, and JavaScript/jQuery in order to implement client-approved designs. Ralph of-
ficially joined the jQuery team as an evangelist in October 2009. Ralph enjoys spending
time with his wife, Hope, and his three boys, Brandon, Jordan, and Ralphie. You can
find out more about Ralph on his personal blog.
Nathan Smith is a goofy guy who has been building websites since late last century.
He enjoys hand-coding HTML, CSS, and JavaScript. He also dabbles in design and
information architecture. He has written for online and paper publications such as
Adobe Developer Center, Digital Web, and .NET Magazine. He has spoken at venues
including Adobe MAX, BibleTech, Drupal Camp, Echo Conference, Ministry 2.0, Re-
fresh Dallas, and Webmaster Jam Session. Nathan works as a UX developer at Fellow-
shipTech.com. He holds a Master of Divinity degree from Asbury Theological Semi-
nary. He started Godbit.com, a community resource aimed at helping churches and
ministries make better use of the Web. He also created the 960 Grid System, a frame-
work for sketching, designing, and coding page layouts.
Brian Cherne is a software developer with more than a decade of experience blue-
printing and building web-based applications, kiosks, and high-traffic e-commerce
websites. He is also the author of the hoverIntent jQuery plugin. When not geeking
out with code, Brian can be found ballroom dancing, practicing martial arts, or studying
Russian culture and language.
xiv | Contributors
Jörn Zaefferer is a professional software developer from Cologne, Germany. He cre-
ates application programming interfaces (APIs), graphical user interfaces (GUIs), soft-
ware architectures, and databases, for both web and desktop applications. His work
focuses on the Java platform, while his client-side scripting revolves around jQuery.
He started contributing to jQuery in mid-2006 and has since cocreated and maintained
QUnit, jQuery’s unit testing framework; released and maintained a half dozen very
popular jQuery plugins; and contributed to jQuery books as both author and tech
reviewer. He is also a lead developer for jQuery UI.
James Padolsey is an enthusiastic web developer and blogger based in London, UK.
He’s been crazy about jQuery since he first discovered it; he’s written tutorials teaching
it, articles and blog posts discussing it, and plenty of plugins for the community. James’
plans for the future include a computer science degree from the University of Kent and
a career that allows him to continually push boundaries. His website is http://james
.padolsey.com.
Scott González is a web application developer living in Raleigh, North Carolina, who
enjoys building highly dynamic systems and flexible, scalable frameworks. He has been
contributing to jQuery since 2007 and is currently the development lead for jQuery UI,
jQuery’s official user interface library. Scott also writes tutorials about jQuery and
jQuery UI on nemikor.com and speaks about jQuery at conferences.
MichaelGearystarteddevelopingsoftwarewheneditingcodemeantpunchingapaper
tape on a Teletype machine, and “standards-compliant” meant following ECMA-10
Standard for Data Interchange on Punched Tape. Today Mike is a web and Android
developer with a particular interest in writing fast, clean, and simple code, and he enjoys
helping other developers on the jQuery mailing lists. Mike’s recent projects include a
series of 2008 election result and voter information maps for Google; and StrataLogic,
a mashup of traditional classroom wall maps and atlases overlaid on Google Earth. His
website is http://mg.to.
Maggie Wachs, Scott Jehl, Todd Parker, and Patty Toland are Filament Group.
Together, they design and develop highly functional user interfaces for consumer- and
business-oriented websites, wireless devices, and installed and web-based applications,
with a specific focus on delivering intuitive and usable experiences that are also broadly
accessible. They are sponsor and design leads of the jQuery UI team, for whom they
designed and developed ThemeRoller.com, and they actively contribute to ongoing
development of the official jQuery UI library and CSS Framework.
Richard D. Worth is a web UI developer. He is the release manager for jQuery UI and
one of its longest-contributing developers. He is author or coauthor of the Dialog,
Progressbar,Selectable,andSliderplugins.Richardalsoenjoysspeakingandconsulting
on jQuery and jQuery UI around the world. Richard is raising a growing family in
Northern Virginia (Washington, D.C. suburbs) with his lovely wife, Nancy. They have
been blessed to date with three beautiful children: Naomi, Asher, and Isaiah.
Richard’s website is http://rdworth.org/.
Contributors | xv
Tech Editors
Karl Swedberg, after having taught high school English, edited copy for an advertising
agency, and owned a coffee house, began his career as a web developer four years ago.
He now works for Fusionary Media in Grand Rapids, Michigan, where he specializes
in client-side scripting and interaction design. Karl is a member of the jQuery project
team and coauthor of Learning jQuery 1.3 and jQuery Reference Guide (both published
by Packt). You can find some of his tips and tutorials at http://www.learningjquery.com.
Dave Methvin is the chief technology officer at PCPitstop.com and one of the founding
partners of the company. He has been using jQuery since 2006, is active on the jQuery
help groups, and has contributed several popular jQuery plugins including Corner and
Splitter. Before joining PC Pitstop, Dave served as executive editor at both PC Tech
Journal and Windows Magazine, where he wrote a column on JavaScript. He continues
to write for several PC-related websites including InformationWeek. Dave holds bach-
elor’s and master’s degrees in computer science from the University of Virginia.
David Serduke is a frontend programmer who is recently spending much of his time
server side. After programming for many years, he started using jQuery in late 2007
and shortly after joined the jQuery core team. David is currently creating websites for
financial institutions and bringing the benefits of jQuery to ASP.NET enterprise ap-
plications. David lives in northern California where he received a bachelor’s degree
from the University of California at Berkeley in electrical engineering and an MBA from
St. Mary’s College.
ScottMarkisanenterpriseapplicationarchitectatMedtronic.Heworksonweb-based
personalized information portals and transactional applications with an eye toward
maintaining high usability in a regulated environment. His key interest areas at the
moment are rich Internet applications and multitouch user interface technologies. Scott
lives in Minnesota with his lovely wife, two sons, and a black lab. He blogs about
technology at http://scottmark.wordpress.com and long-distance trail running at http://
runlikemonkey.com.
xvi | Contributors
Preface
The jQuery library has taken the frontend development world by storm. Its dead-simple
syntax makes once-complicated tasks downright trivial—enjoyable, even. Many a de-
veloper has been quickly seduced by its elegance and clarity. If you’ve started using the
library, you’re already adding rich, interactive experiences to your projects.
Getting started is easy, but as is the case with many of the tools we use to develop
websites, it can take months or even years to fully appreciate the breadth and depth of
the jQuery library. The library is chock-full of features you might never have known to
wish for. Once you know about them, they can dramatically change how you approach
the problems you’re called upon to solve.
The goal of this cookbook is to expose you, dear reader, to the patterns and practices
of some of the leading frontend developers who use jQuery in their everyday projects.
Over the course of 18 chapters, they’ll guide you through solutions to problems that
range from straightforward to complex. Whether you’re a jQuery newcomer or a griz-
zled JavaScript veteran, you’re likely to gain new insight into harnessing the full power
of jQuery to create compelling, robust, high-performance user interfaces.
Who This Book Is For
Maybe you’re a designer who is intrigued by the interactivity that jQuery can provide.
Maybe you’re a frontend developer who has worked with jQuery before and wants to
see how other people accomplish common tasks. Maybe you’re a server-side developer
who’s frequently called upon to write client-side code.
Truth be told, this cookbook will be valuable to anyone who works with jQuery—or
who hopes to work with jQuery. If you’re just starting out with the library, you may
want to consider pairing this book with Learning jQuery 1.3 from Packt, or jQuery in
Action from Manning. If you’re already using jQuery in your projects, this book will
serve to enhance your knowledge of the library’s features, hidden gems, and
idiosyncrasies.
xvii
What You’ll Learn
We’ll start out by covering the basics and general best practices—including jQuery in
your page, making selections, and traversing and manipulation. Even frequent jQuery
users are likely to pick up a tip or two. From there, we move on to real-world use cases,
walking you through tried-and-true (and tested) solutions to frequent problems
involving events, effects, dimensions, forms, and user interface elements (with and
without the help of jQuery UI). At the end, we’ll take a look at testing your jQuery
applications and integrating jQuery into complex sites.
Along the way, you’ll learn strategies for leveraging jQuery to solve problems that go
far beyond the basics. We’ll explore how to make the most of jQuery’s event manage-
ment system, including custom events and custom event data; how to progressively
enhance forms; how to position and reposition elements on the page; how to create
user interface elements such as tabs, accordions, and modals from scratch; how to craft
yourcodeforreadabilityandmaintainability;howtooptimizeyourcodetoeasetesting,
eliminate bottlenecks, and ensure peak performance; and more.
Because this is a cookbook and not a manual, you’re of course welcome to cherry-pick
the recipes you read; the individual recipes alone are worth the price of admission. As
a whole, though, the book provides a rare glimpse into the problem-solving approaches
of some of the best and brightest in the jQuery community. With that in mind, we
encourage you to at least skim it from front to back—you never know which line of
code will provide the “Aha!” moment you need to take your skills to the next level.
jQuery Style and Conventions
jQuery places a heavy emphasis on chaining—calling methods on element selections
in sequence, confident in the knowledge that each method will give you back a selection
of elements you can continue to work with. This pattern is explained in depth in
Chapter 1—if you’re new to the library, you’ll want to understand this concept, because
it is used heavily in subsequent chapters.
jQuery’s features are organized into a handful of simple categories: core functionality,
selecting, manipulating, traversing, CSS, attributes, events, effects, Ajax, and utilities.
Learning these categories, and how methods fit into them, will greatly enhance your
understanding of the material in this book.
One of the best practices this book will cover is the concept of storing element selections
in a variable, rather than making the same selection repeatedly. When a selection is
stored in a variable, it is commonplace for that variable to begin with the $ character,
indicating that it is a jQuery object. This can make code easier to read and maintain,
butitshouldbeunderstoodthatstartingthevariablenamewiththe$ characterismerely
a convention; it carries no special meaning, unlike in other languages such as PHP.
xviii | Preface
In general, the code examples in this book strive for clarity and readability over com-
pactness, so the examples may be more verbose than is strictly necessary. If you see an
opportunity for optimization, you should not hesitate to take it. At the same time, you’ll
do well to strive for clarity and readability in your own code and use minification tools
to prepare your code for production use.
Other Options
If you’re looking for other jQuery resources, here are some we recommend:
• Learning jQuery 1.3, by Jonathan Chaffer, Karl Swedberg, and John Resig (Packt)
• jQuery in Action, by Bear Bibeault, Yehuda Katz, and John Resig (Manning)
• jQuery UI 1.6: The User Interface Library for jQuery, by Dan Wellman (Packt)
If You Have Problems Making Examples Work
Before you check anything else, ensure that you are loading the jQuery library on the
page—you’d be surprised how many times this is the solution to the “It’s not working!”
problem. If you are using jQuery with another JavaScript library, you may need to use
jQuery.noConflict() to make it play well with others. If you’re loading scripts that
require the presence of jQuery, make sure you are loading them after you’ve loaded the
jQuery library.
Much of the code in this book requires the document to be “ready” before JavaScript
can interact with it. If you’ve included code in the head of the document, make sure
your code is enclosed in $(document).ready(function() { ... }); so that it knows to
wait until the document is ready for interaction.
Some of the features discussed in this book are available only in jQuery 1.3 and later.
If you are upgrading from an older version of jQuery, make sure you’ve upgraded any
plugins you’re using as well—outdated plugins can lead to unpredictable behavior.
If you’re having difficulty getting an example to work in an existing application, make
sure you can get the example working on its own before trying to integrate it with your
existing code. If that works, tools such as Firebug for the Firefox browser can be useful
in identifying the source of the problem.
If you’re including a minified version of jQuery and running into errors that point to
the jQuery library itself, you may want to consider switching to the full version of
jQuery while you are debugging the issue. You’ll have a much easier time locating the
line that is causing you trouble, which will often lead you in the direction of a solution.
If you’re still stuck, consider posting your question to the jQuery Google group. Many
of this book’s authors are regular participants in the group, and more often than not,
someone in the group will be able to offer useful advice. The #jquery IRC channel on
Freenode is another valuable resource for troubleshooting issues.
Preface | xix
If none of this works, it’s possible we made a mistake. We worked hard to test and
review all of the code in the book, but errors do creep through. Check the errata (de-
scribed in the next section) and download the sample code, which will be updated to
address any errata we discover.
If You Like (or Don’t Like) This Book
If you like—or don’t like—this book, by all means, please let people know. Amazon
reviews are one popular way to share your happiness (or lack of happiness), or you can
leave reviews at the site for the book:
http://oreilly.com/catalog/9780596159771/
There’s also a link to errata there. Errata gives readers a way to let us know about typos,
errors, and other problems with the book. That errata will be visible on the page im-
mediately, and we’ll confirm it after checking it out. O’Reilly can also fix errata in future
printingsofthebookandonSafari,makingforabetterreaderexperienceprettyquickly.
We hope to keep this book updated for future versions of jQuery, and will also incor-
porate suggestions and complaints into future editions.
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates Internet addresses, such as domain names and URLs, and new items
where they are defined.
Constant width
Indicates command lines and options that should be typed verbatim; names and
keywords in programs, including method names, variable names, and class names;
and HTML element tags, switches, attributes, keys, functions, types, namespaces,
modules, properties, parameters, values, objects, events, event handlers, macros,
the contents of files, or the output from commands.
Constant width bold
Indicates emphasis in program code lines.
Constant width italic
Indicates text that should be replaced with user-supplied values.
This icon signifies a tip, suggestion, or general note.
xx | Preface
This icon indicates a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code in
this book in your programs and documentation. You do not need to contact us for
permission unless you’re reproducing a significant portion of the code. For example,
writing a program that uses several chunks of code from this book does not require
permission. Answering a question by citing this book and quoting example code does
not require permission. Selling or distributing a CD-ROM of examples from O’Reilly
books does require permission. Incorporating a significant amount of example code
from this book into your product’s documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title,
author, publisher, and ISBN. For example: “jQuery Cookbook, by Cody Lindley. Copy-
right 2010 Cody Lindley, 978-0-596-15977-1.” If you feel your use of code examples
falls outside fair use or the permission given above, feel free to contact us at
permissions@oreilly.com.
Safari® Books Online
Safari Books Online is an on-demand digital library that lets you easily
search over 7,500 technology and creative reference books and videos to
find the answers you need quickly.
Withasubscription,youcanreadanypageandwatchanyvideofromourlibraryonline.
Read books on your cell phone and mobile devices. Access new titles before they are
available for print, and get exclusive access to manuscripts in development and post
feedback for the authors. Copy and paste code samples, organize your favorites, down-
load chapters, bookmark key sections, create notes, print out pages, and benefit from
tons of other time-saving features.
O’Reilly Media has uploaded this book to the Safari Books Online service. To have full
digital access to this book and others on similar topics from O’Reilly and other pub-
lishers, sign up for free at http://my.safaribooksonline.com.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
Preface | xxi
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
To comment or ask technical questions about this book, send email to:
bookquestions@oreilly.com
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:
http://oreilly.com
—Rebecca Murphey and Cody Lindley
xxii | Preface
CHAPTER 1
jQuery Basics
Cody Lindley
1.0 Introduction
Since you’ve picked up a cookbook about jQuery, the authors of this book for the most
part are going to assume that you have a loose idea about what exactly jQuery is and
what it does. Frankly, cookbooks in general are typically written for an audience who
seeks to enhance a foundation of knowledge that has already been established. Thus,
the recipe-solution-discussion format is used to quickly get you solutions to common
problems. However, if you are a jQuery newbie, don’t throw this book against the wall
and curse us just yet. We’ve dedicated this chapter to you.
If you are in need of a review or are jumping into this cookbook with little or no working
knowledge of jQuery, this first chapter alone (the other chapters assume you know the
basics) will aid you in learning the jQuery essentials. Now, realistically, if you have
absolutely zero knowledge of JavaScript and the DOM, you might want to take a step
back and ask yourself whether approaching jQuery without a basic understanding of
the JavaScript core language and its relationship with the DOM is plausible. It would
be my recommendation to study up on the DOM and JavaScript core before approach-
ing jQuery. I highly recommend JavaScript: The Definitive Guide by David Flanagan
(O’Reilly) as a primer before reading this book. But don’t let my humble opinion stop
you if you are attempting to learn jQuery before you learn about the DOM and Java-
Script. Many have come to a working knowledge of these technologies by way of
jQuery. And while not ideal, let’s face it, it can still be done.
With that said, let’s take a look at a formal definition of jQuery and a brief description
of its functionality:
jQuery is an open source JavaScript library that simplifies the interactions between an
HTML document, or more precisely the Document Object Model (aka the DOM), and
JavaScript.
In plain words, and for the old-school JavaScript hackers out there, jQuery makes Dy-
namic HTML (DHTML) dead easy. Specifically, jQuery simplifies HTML document
1
traversing and manipulation, browser event handling, DOM animations, Ajax inter-
actions, and cross-browser JavaScript development.
With a formal explanation of jQuery under our belts, let’s next explore why you might
choose to use jQuery.
Why jQuery?
It might seem a bit silly to speak about the merits of jQuery within this cookbook,
especially since you’re reading this cookbook and are likely already aware of the merits.
So, while I might be preaching to the choir here, we’re going to take a quick look at
why a developer might choose to use jQuery. My point in doing this is to foster your
basic knowledge of jQuery by first explaining the “why” before we look at the “how.”
In building a case for jQuery, I’m not going to compare jQuery to its competitors in
order to elevate jQuery’s significance. That’s because I just don’t believe that there
really is a direct competitor. Also, I believe the only library available today that meets
the needs of both designer types and programmer types is jQuery. In this context,
jQuery is in a class of its own.
Of the notorious JavaScript libraries and frameworks in the wild, I truly believe each
has its own niche and value. A broad comparison is silly, but it’s nevertheless attempted
all the time. Heck, I am even guilty of it myself. However, after much thought on the
topic, I truly believe that all JavaScript libraries are good at something. They all have
value. What makes one more valuable than the other depends more upon who is using
it and how it’s being used than what it actually does. Besides, it has been my observation
that micro differences across JavaScript libraries are often trivial in consideration of the
broader goals of JavaScript development. So, without further philosophical ramblings,
here is a list of attributes that builds a case for why you should use jQuery:
• It’s open source, and the project is licensed under an MIT and a GNU General
Public License (GPL) license. It’s free, yo, in multiple ways!
• It’s small (18 KB minified) and gzipped (114 KB, uncompressed).
• It’s incredibly popular, which is to say it has a large community of users and a
healthy amount of contributors who participate as developers and evangelists.
• It normalizes the differences between web browsers so that you don’t have to.
• It’s intentionally a lightweight footprint with a simple yet clever plugin
architecture.
• Its repository of plugins is vast and has seen steady growth since jQuery’s release.
• Its API is fully documented, including inline code examples, which in the world
of JavaScript libraries is a luxury. Heck, any documentation at all was a luxury for
years.
• It’s friendly, which is to say it provides helpful ways to avoid conflicts with other
JavaScript libraries.
2 | Chapter 1: jQuery Basics
• Its community support is actually fairly useful, including several mailing lists, IRC
channels, and a freakishly insane amount of tutorials, articles, and blog posts from
the jQuery community.
• It’s openly developed, which means anyone can contribute bug fixes, enhance-
ments, and development help.
• Its development is steady and consistent, which is to say the development team is
not afraid of releasing updates.
• Its adoption by large organizations has and will continue to breed longevity and
stability (e.g., Microsoft, Dell, Bank of America, Digg, CBS, Netflix).
• It’s incorporating specifications from the W3C before the browsers do. As an ex-
ample, jQuery supports a good majority of the CSS3 selectors.
• It’s currently tested and optimized for development on modern browsers
(Chrome 1, Chrome Nightly, IE 6, IE 7, IE 8, Opera 9.6, Safari 3.2, WebKit Nightly,
Firefox 2, Firefox 3, Firefox Nightly).
• It’s downright powerful in the hands of designer types as well as programmers.
jQuery does not discriminate.
• Its elegance, methodologies, and philosophy of changing the way JavaScript is
written is becoming a standard in and of itself. Consider just how many other
solutions have borrowed the selector and chaining patterns.
• Its unexplainable by-product of feel-good programming is contagious and certainly
unavoidable; even the critics seem to fall in love with aspects of jQuery.
• Its documentation has many outlets (e.g., API browser, dashboard apps, cheat
sheets) including an offline API browser (AIR application).
• It’s purposely bent to facilitate unobtrusive JavaScript practices.
• It has remained a JavaScript library (as opposed to a framework) at heart while at
the same time providing a sister project for user interface widgets and application
development (jQuery UI).
• Its learning curve is approachable because it builds upon concepts that most de-
velopers and designers already understand (e.g., CSS and HTML).
It is my opinion that the combination of the aforementioned jQuery points, and not
any single attribute on its own, sets it apart from all other solutions. The total jQuery
package is simply unmatched as a JavaScript tool.
The jQuery Philosophy
The jQuery philosophy is “Write less, do more.” This philosophy can be further broken
down into three concepts:
• Finding some elements (via CSS selectors) and doing something with them (via
jQuery methods)
• Chaining multiple jQuery methods on a set of elements
1.0 Introduction | 3
• Using the jQuery wrapper and implicit iteration
Understanding these three concepts in detail is foundational when it comes time to
write your own jQuery code or augment the recipes found in this book. Let’s examine
each of these concepts in detail.
Find some elements and do something with them
Or more specifically stated, locate a set of elements in the DOM, and then do something
with that set of elements. For example, let’s examine a scenario where you want to hide
a <div> from the user, load some new text content into the hidden <div>, change an
attribute of the selected <div>, and then finally make the hidden <div> visible again.
This last sentence translated into jQuery code would look something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div>old content</div>
<script>
//hide all divs on the page
jQuery('div').hide();
//update the text contained inside of all divs
jQuery('div').text('new content');
//add a class attribute with a value of updatedContent to all divs
jQuery('div').addClass("updatedContent");
//show all divs on the page
jQuery('div').show();
</script>
</body>
</html>
Let’s step through these four jQuery statements:
• Hide the <div> element on the page so it’s hidden from the user’s view.
• Replace the text inside the hidden <div> with some new text (new content).
• Update the <div> element with a new attribute (class) and value (updatedContent).
• Show the <div> element on the page so it’s visible again to the viewing user.
If the jQuery code at this point is mystical syntax to you, that’s OK. We’ll dive into the
basics with the first recipe in this chapter. Again, what you need to take away from this
code example is the jQuery concept of “find some elements and do something with
4 | Chapter 1: jQuery Basics
them.” In our code example, we found all the <div> elements in the HTML page using
the jQuery function (jQuery()), and then using jQuery methods we did something with
them (e.g., hide(), text(), addClass(), show()).
Chaining
jQuery is constructed in a manner that will allow jQuery methods to be chained. For
example, why not find an element once and then chain operations onto that element?
Our former code example demonstrating the “Find some elements and do something
with them” concept could be rewritten to a single JavaScript statement using chaining.
This code, using chaining, can be changed from this:
//hide all divs on the page
jQuery('div').hide();
//update the text contained inside of the div
jQuery('div').text('new content');
//add a class attribute with a value of updatedContent to all divs
jQuery('div').addClass("updatedContent");
//show all divs on the page
jQuery('div').show();
to this:
jQuery('div').hide().text('new content').addClass("updatedContent").show();
or, with indenting and line breaks, to this:
jQuery('div')
.hide()
.text('new content')
.addClass("updatedContent")
.show();
Plainly speaking, chaining simply allows you to apply an endless chain of jQuery meth-
ods on the elements that are currently selected (currently wrapped with jQuery func-
tionality)usingthejQueryfunction.Behindthescenes,theelementspreviouslyselected
before a jQuery method was applied are always returned so that the chain can continue.
As you will see in future recipes, plugins are also constructed in this manner (returning
wrapped elements) so that using a plugin does not break the chain.
If it’s not immediately obvious, and based on the code in question, chaining also cuts
down on processing overhead by selecting a set of DOM elements only once, to then
be operated on numerous times by jQuery methods by way of chaining. Avoiding un-
necessary DOM traversing is a critical part of page performance enhancements. When-
ever possible, reuse or cache a set of selected DOM elements.
1.0 Introduction | 5
The jQuery wrapper set
A good majority of the time, if jQuery is involved, you’re going to be getting what is
known as a wrapper. In other words, you’ll be selecting DOM elements from an HTML
page that will be wrapped with jQuery functionality. Personally, I often refer to this as
a “wrapper set” or “wrapped set” because it’s a set of elements wrapped with jQuery
functionality. Sometimes this wrapper set will contain one DOM element; other times
it will contain several. There are even cases where the wrapper set will contain no
elements. In these situations, the methods/properties that jQuery provides will fail
silently if methods are called on an empty wrapper set, which can be handy in avoiding
unneeded if statements.
Now, based on the code we used to demonstrate the “Find some elements and do
something with them” concept, what do you think would happen if we added multiple
<div> elements to the web page? In the following updated code example, I have added
three additional <div> elements to the HTML page, for a total of four <div> elements:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/
jquery/1.3.0/jquery.min.js"></script> </head>
<body>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<div>old content</div>
<script>
//hide all divs on the page
jQuery('div').hide().text('new content').addClass("updatedContent").show();
</script>
</body>
</html>
You may not have explicitly written any programmatic loops here, but guess what?
jQuery is going to scan the page and place all <div> elements in the wrapper set so that
the jQuery methods I am using here are performed (aka implicit iteration) on each
DOM element in the set. For example, the .hide() method actually applies to each
element in the set. So if you look at our code again, you will see that each method that
we use will be applied to each <div> element on the page. It’s as if you had written a
loop here to invoke each jQuery method on each DOM element. The updated code
example will result in each <div> in the page being hidden, filled with updated text,
given a new class value, and then made visible again.
Wrapping your head around (pun intended) the wrapper set and its default looping
system (aka implicit iteration) is critical for building advanced concepts around loop-
ing. Just keep in mind that a simple loop is occurring here before you actually do any
additional looping (e.g., jQuery('div').each(function(){}). Or another way to look at
6 | Chapter 1: jQuery Basics
this is each element in the wrapper will typically be changed by the jQuery method(s)
that are called.
Something to keep in mind here is there are scenarios that you will learn about in the
coming chapters where only the first element, and not all the elements in the wrapper
set, is affected by the jQuery method (e.g., attr()).
How the jQuery API Is Organized
There is no question that when I first started out with jQuery, my main reason for
selecting it as my JavaScript library was simply that it had been properly documented
(and the gazillion plugins!). Later, I realized another factor that cemented my love affair
with jQuery was the fact that the API was organized into logical categories. Just by
looking at how the API was organized, I could narrow down the functionality I needed.
Before you really get started with jQuery, I suggest visiting the documentation online
and simply digesting how the API is organized. By understanding how the API is or-
ganized, you’ll more quickly navigate the documentation to the exact information you
need, which is actually a significant advantage given that there are really a lot of different
ways to code a jQuery solution. It’s so robust that it’s easy to get hung up on imple-
mentation because of the number of solutions for a single problem. I’ve replicated here
for you how the API is organized. I suggest memorizing the API outline, or at the very
least the top-level categories.
• jQuery Core
—The jQuery Function
—jQuery Object Accessors
—Data
—Plugins
—Interoperability
• Selectors
—Basics
—Hierarchy
—Basic Filters
—Content Filters
—Visibility Filters
—Attribute Filters
—Child Filters
—Forms
—Form Filters
• Attributes
1.0 Introduction | 7
—Attr
—Class
—HTML
—Text
—Value
• Traversing
—Filtering
—Finding
—Chaining
• Manipulation
—Changing Contents
—Inserting Inside
—Inserting Outside
—Inserting Around
—Replacing
—Removing
—Copying
• CSS
—CSS
—Positioning
—Height and Widths
• Events
—Page Load
—Event Handling
—Live Events
—Interaction Helpers
—Event Helpers
• Effects
—Basics
—Sliding
—Fading
—Custom
—Settings
• Ajax
—AJAX Requests
8 | Chapter 1: jQuery Basics
—AJAX Events
—Misc.
• Utilities
—Browser and Feature Detection
—Array and Object Operations
—Test Operations
—String Operations
—Urls
Before we jump into a sequence of basic jQuery recipes, I would like to mention that
the recipes found in this chapter build on each other. That is, there is a logical formation
of knowledge as you progress from the first recipe to the last. It’s my suggestion, for
your first reading of these recipes, that you read them in order from 1.1 to 1.17.
1.1 Including the jQuery Library Code in an HTML Page
Problem
You want to use the jQuery JavaScript library on a web page.
Solution
There are currently two ideal solutions for embedding the jQuery library in a web page:
• Use the Google-hosted content delivery network (CDN) to include a version of
jQuery (used in this chapter).
• Download your own version of jQuery from jQuery.com and host it on your own
server or local filesystem.
Discussion
Including the jQuery JavaScript library isn’t any different from including any other
external JavaScript file. You simply use the HTML <script> element and provide the
element a value (URL or directory path) for its src="" attribute, and the external file
you are linking to will be included in the web page. For example, the following is a
template that includes the jQuery library that you can use to start any jQuery project:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
1.1 Including the jQuery Library Code in an HTML Page | 9
<script type="text/JavaScript">
alert('jQuery ' + jQuery.fn.jquery);
</script>
</body>
</html>
Notice that I am using—and highly recommend using for public web pages—the
Google-hosted minified version of jQuery. However, debugging JavaScript errors in
minified code is not ideal. During code development, or on the production site, it ac-
tually might be better to use the nonminified version from Google for the purpose of
debugging potential JavaScript errors. For more information about using the Google-
hosted version of jQuery, you can visit the Ajax libraries API site on the Web at http://
code.google.com/apis/ajaxlibs/.
It’s of course also possible, and mostly likely old hat, to host a copy of the jQuery code
yourself. In most circumstances, however, this would be silly to do because Google has
been kind enough to host it for you. By using a Google-hosted version of jQuery, you
benefit from a stable, reliable, high-speed, and globally available copy of jQuery. As
well, you reap the benefit of decreased latency, increased parallelism, and better cach-
ing.ThisofcoursecouldbeaccomplishedwithoutusingGoogle’ssolution,butitwould
most likely cost you a dime or two.
Now, for whatever reason, you might not want to use the Google-hosted version of
jQuery. You might want a customized version of jQuery, or your usage might not
require/haveaccesstoanInternetconnection.Or,yousimplymightbelievethatGoogle
is “The Man” and wish not to submit to usage because you are a control freak and
conspiracy fanatic. So, for those who do not need, or simply who do not want, to use
a Google-hosted copy of the jQuery code, jQuery can be downloaded from
jQuery.com and hosted locally on your own server or local filesystem. Based on the
template I’ve provided in this recipe, you would simply replace the src attribute value
with a URL or directory path to the location of the jQuery JavaScript file you’ve down-
loaded.
1.2 Executing jQuery/JavaScript Coded After the DOM Has
Loaded but Before Complete Page Load
Problem
Modern JavaScript applications using unobtrusive JavaScript methodologies typically
executeJavaScriptcodeonlyaftertheDOMhasbeencompletelyloaded.Andthereality
ofthesituationisthatanyDOMtraversingandmanipulationwillrequirethattheDOM
is loaded before it can be operated on. What’s needed is a way to determine when the
client, most often a web browser, has completely loaded the DOM but has possibly not
yet completely loaded all assets such as images and SWF files. If we were to use the
window.onload event in this situation, the entire document including all assets would
10 | Chapter 1: jQuery Basics
need to be completely loaded before the onload event fired. That’s just too time-
consuming for most web surfers. What’s needed is an event that will tell us when the
DOM alone is ready to be traversed and manipulated.
Solution
jQuery provides the ready() method, which is a custom event handler that is typically
bound to the DOM’s document object. The ready() method is passed a single param-
eter, a function, that contains the JavaScript code that should be executed once the
DOM is ready to be traversed and manipulated. The following is a simple example of
this event opening an alert() window once the DOM is ready but before the page is
completely loaded:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery(document).ready(function(){//DOM not loaded, must use ready event
alert(jQuery('p').text());
});
</script>
</head>
<body>
<p>The DOM is ready!</p>
</body>
</html>
Discussion
The ready() event handler method is jQuery’s replacement for using the JavaScript core
window.onload event. It can be used as many times as you like. When using this custom
event, it’s advisable that it be included in your web pages after the inclusion of stylesheet
declarations and includes. Doing this will ensure that all element properties are cor-
rectly defined before any jQuery code or JavaScript code will be executed by the
ready() event.
Additionally, the jQuery function itself provides a shortcut for using the jQuery custom
ready event. Using this shortcut, the following alert() example can be rewritten like so:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery(function(){ //DOM not loaded, must use ready event
1.2 Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load | 11
alert(jQuery('p').text());
});
</script>
</head>
<body>
<p>The DOM is ready!</p>
</body>
</html>
The use of this custom jQuery event is necessary only if JavaScript has to be embedded
in the document flow at the top of the page and encapsulated in the <head> element. I
simply avoid the usage of the ready() event by placing all JavaScript includes and inline
code before the closing <body> element. I do this for two reasons.
First, modern optimization techniques have declared that pages load faster when the
JavaScript is loaded by the browser at the end of a page parse. In other words, if you
put JavaScript code at the bottom of a web page, then the browser will load everything
in front of it before it loads the JavaScript. This is a good thing because most browsers
will typically stop processing other loading initiatives until the JavaScript engine has
compiled the JavaScript contained in a web page. It’s sort of a bottleneck in a sense
that you have JavaScript at the top of a web page document. I realize that for some
situations it’s easier to place JavaScript in the <head> element. But honestly, I’ve never
seen a situation where this is absolutely required. Any obstacle that I’ve encountered
during my development by placing JavaScript at the bottom of the page has been easily
overcome and well worth the optimization gains.
Second, if speedy web pages are our goal, why wrap more functionality around a sit-
uation that can be elevated by simply moving the code to the bottom of the page? When
given the choice between more code or less code, I choose less code. Not using the
ready() event results in using less code, especially since less code always runs faster
than more code.
With some rationale out of the way, here is an example of our alert() code that does
not use the ready() event:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>The DOM is ready!</p>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
alert(jQuery('p').text());//go for it the DOM is loaded
</script>
</body>
</html>
12 | Chapter 1: jQuery Basics
Notice that I have placed all of my JavaScript before the closing </body> element. Any
additional markup should be placed above the JavaScript in the HTML document.
1.3 Selecting DOM Elements Using Selectors and the jQuery
Function
Problem
You need to select a single DOM element and/or a set of DOM elements in order to
operate on the element(s) using jQuery methods.
Solution
jQuery provides two options when you need to select element(s) from the DOM. Both
options require the use of the jQuery function (jQuery() or alias $()). The first option,
which uses CSS selectors and custom selectors, is by far the most used and most elo-
quent solution. By passing the jQuery function a string containing a selector expression,
the function will traverse the DOM and locate the DOM nodes defined by the expres-
sion. As an example, the following code will select all the <a> elements in the HTML
document:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
//alerts there are 6 elements
alert('Page contains ' + jQuery('a').length + ' <a> elements!');
</script>
</body>
</html>
If you were to run this HTML page in a web browser, you would see that the code
executes a browser alert() that informs us that the page contains six <a> elements. I
passed this value to the alert() method by first selecting all the <a> elements and then
using the length property to return the number of elements in the jQuery wrapper set.
1.3 Selecting DOM Elements Using Selectors and the jQuery Function | 13
You should be aware that the first parameter of the jQuery function, as we are using it
here, will also accept multiple expressions. To do this, simply separate multiple selec-
tors with a comma inside the same string that is passed as the first parameter to the
jQuery function. Here is an example of what that might look like:
jQuery('selector1, selector2, selector3').length;
Our second option for selecting DOM elements and the less common option is to pass
the jQuery function an actual JavaScript reference to DOM element(s). As an example,
the following code will select all the <a> elements in the HTML document. Notice that
I’m passing the jQuery function an array of <a> elements collected using the
getElementsByTagName DOM method. This example produces the same exact results as
our previous code example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body bgcolor="yellow"> <!-- yes the attribute is depreciated, I know, roll
with it -->
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<a href='#'>link</a>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
//alerts there are 6 elements
alert('Page contains ' + jQuery(document.getElementsByTagName('a')).length +
' <a> Elements, And has a '
+ jQuery(document.body).attr('bgcolor') + ' background');
</script>
</body>
</html>
Discussion
The heavy lifting that jQuery is known for is partially based on the selector engine,
Sizzle, that selects DOM element(s) from an HTML document. While you have the
option, and it’s a nice option when you need it, passing the jQuery function DOM
references is not what put jQuery on everyone’s radar. It’s the vast and powerful options
available with selectors that make jQuery so unique.
Throughout the rest of the book, you will find powerful and robust selectors. When
you see one, make sure you fully understand its function. This knowledge will serve
you well with future coding endeavors using jQuery.
14 | Chapter 1: jQuery Basics
1.4 Selecting DOM Elements Within a Specified Context
Problem
You need a reference to a single DOM element or a set of DOM elements in the context
of another DOM element or document in order to operate on the element(s) using
jQuery methods.
Solution
The jQuery function when passed a CSS expression will also accept a second parameter
that tells the jQuery function to which context it should search for the DOM elements
based on the expression. The second parameter in this case can be a DOM reference,
jQuery wrapper, or document. In the following code, there are 12 <input> elements.
Notice how I use a specific context, based on the <form> element, to select only par-
ticular <input> elements:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form>
<input name="" type="checkbox" />
<input name="" type="radio" />
<input name="" type="text" />
<input name="" type="button" />
</form>
<form>
<input name="" type="checkbox" />
<input name="" type="radio" />
<input name="" type="text" />
<input name="" type="button" />
</form>
<input name="" type="checkbox" />
<input name="" type="radio" />
<input name="" type="text" />
<input name="" type="button" />
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
//searches within all form elements, using a wrapper for context, alerts "8 inputs"
alert('selected ' + jQuery('input',$('form')).length + ' inputs');
//search with the first form element, using DOM reference as the context, alerts
1.4 Selecting DOM Elements Within a Specified Context | 15
//"4 inputs"
alert('selected' + jQuery('input',document.forms[0]).length + ' inputs');
//search within the body element for all input elements using an expression,
//alerts "12 inputs"
alert('selected' + jQuery('input','body').length + ' inputs');
</script>
</body>
</html>
Discussion
It’s also possible, as mentioned in the solution of this recipe, to select documents as
the context for searching. For example, it’s possible to search within the context of an
XML document that is sent back from doing an XHR request (Ajax). You can find more
details about this usage in Chapter 16.
1.5 Filtering a Wrapper Set of DOM Elements
Problem
You have a set of selected DOM elements in a jQuery wrapper set but want to remove
DOM elements from the set that do not match a new specified expression(s) in order
to create a new set of elements to operate on.
Solution
The jQuery filter method, used on a jQuery wrapper set of DOM elements, can exclude
elements that do not match a specified expression(s). In short, the filter() method
allows you to filter the current set of elements. This is an important distinction from
the jQuery find method, which will reduce a wrapped set of DOM elements by finding
(via a new selector expression) new elements, including child elements of the current
wrapped set.
To understand the filter method, let’s examine the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<a href="#" class="external">link</a>
<a href="#" class="external">link</a>
<a href="#"></a>
<a href="#" class="external">link</a>
<a href="#" class="external">link</a>
<a href="#"></a></li>
16 | Chapter 1: jQuery Basics
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
<a href="#">link</a>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
//alerts 4 left in the set
alert(jQuery('a').filter('.external').length + ' external links');
</script>
</body>
</html>
The HTML page in the code example just shown contains a web page with 10 <a>
elements. Those links that are external links are given a class name of external. Using
the jQuery function, we select all <a> elements on the page. Then, using the filter meth-
od, all those elements that do not have a class attribute value of external are removed
from the original set. Once the initial set of DOM elements are altered using the
filter() method, I invoke the length property, which will tell me how many elements
are now in my new set after the filter has been applied.
Discussion
It’s also possible to send the filter() method a function that can be used to filter the
wrapped set. Our previous code example, which passes the filter() method a string
expression, can be changed to use a function instead:
alert(
jQuery('a')
.filter(function(index){ return $(this).hasClass('external');})
.length + ' external links'
);
Notice that I am now passing the filter() method an anonymous function. This func-
tion is called with a context equal to the current element. That means when I use
$(this) within the function, I am actually referring to each DOM element in the wrap-
per set. Within the function, I am checking each <a> element in the wrapper set to see
whether the element has a class value (hasClass()) of external. If it does, Boolean true,
then keep the element in the set, and if it doesn’t (false), then remove the element from
the set. Another way to look at this is if the function returns false, then the element is
removed. If the function returns any other data value besides false, then the element
will remain in the wrapper set.
You may have noticed that I have passed the function a parameter named index that I
am not using. This parameter, if needed, can be used to refer numerically to the index
of the element in the jQuery wrapper set.
1.5 Filtering a Wrapper Set of DOM Elements | 17
1.6 Finding Descendant Elements Within the Currently
Selected Wrapper Set
Problem
You have a set of selected DOM elements (or a single element) and want to find de-
scendant (children) elements within the context of the currently selected elements.
Solution
Use the .find() method to create a new wrapper set of elements based on the context
of the current set and their descendants. For example, say that you have a web page
that contains several paragraphs. Encapsulated inside of these paragraphs are words
that are emphasized (italic). If you’d like to select only <em> elements contained within
<p> elements, you could do so like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Ut ad videntur facilisis <em>elit</em> cum. Nibh insitam erat facit
<em>saepius</em> magna. Nam ex liber iriure et imperdiet. Et mirum eros
iis te habent. </p>
<p>Claram claritatem eu amet dignissim magna. Dignissim quam elit facer eros
illum. Et qui ex esse <em>tincidunt</em> anteposuerit. Nulla nam odio ii
vulputate feugait.</p>
<p>In quis <em>laoreet</em> te legunt euismod. Claritatem <em>consuetudium</em>
wisi sit velit facilisi.</p>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
//alerts total italic words found inside of <p> elements
alert('The three paragraphs in all contain ' +
jQuery('p').find('em').length + '
italic words');
</script>
</body>
</html>
Keep in mind that we could have also written this code by passing a contextual reference
as a second parameter to the jQuery function:
alert('The three paragraphs in all contain ' + jQuery('em',$('p')).length +
' italic words');
Additionally, it’s worth mentioning that the last two code examples are demonstrative
in purpose. It is likely more logical, if not pragmatic, to use a CSS selector expression
to select all the descendant italic elements contained within the ancestor <p> elements.
18 | Chapter 1: jQuery Basics
alert('The three paragraphs in all contain ' + jQuery('p em').length +
' italic words');
Discussion
ThejQuery.find() methodcanbeusedtocreateanewsetofelementsbasedoncontext
of the current set of DOM elements and their children elements. People often confuse
the use of the .filter() method and .find() method. The easiest way to remember
the difference is to keep in mind that .find() will operate/select the children of the
current set while .filter() will only operate on the current set of elements. In other
words, if you want to change the current wrapper set by using it as a context to further
select the children of the elements selected, use .find(). If you only want to filter the
current wrapped set and get a new subset of the current DOM elements in the set only,
use .filter(). To boil this down even more, find() returns children elements, while
filter() only filters what is in the current wrapper set.
1.7 Returning to the Prior Selection Before a Destructive
Change
Problem
A destructive jQuery method (e.g., filter() or find()) that was used on a set of ele-
ments needs to be removed so that the set prior to the use of the destructive method is
returned to its previous state and can then be operated as if the destructive method had
never been invoked.
Solution
jQuery provides the end() method so that you can return to the previous set of DOM
elements that were selected before using a destructive method. To understand the
end() method, let’s examine the following HTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>text</p>
<p class="middle">Middle <span>text</span></p>
<p>text</p>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
alert(jQuery('p').filter('.middle').length); //alerts 1
alert(jQuery('p').filter('.middle').end().length); //alerts 3
alert(jQuery('p').filter('.middle').find('span')
1.7 Returning to the Prior Selection Before a Destructive Change | 19
.end().end().length); //alerts 3
</script>
</body>
</html>
The first alert() statement in the code contains a jQuery statement that will search the
document for all <p> elements and then apply filter() to the selected <p> elements in
the set selecting only the one(s) with a class of middle. The length property then reports
how many elements are left in the set:
alert(jQuery('p').filter('.middle').length); //alerts 1
The next alert() statement makes use of the end() method. Here we are doing every-
thing we did in the prior statement except that we are undoing the filter() method
and returning to the set of elements contained in the wrapper set before the filter()
method was applied:
alert(jQuery('p').filter('.middle').end().length); //alerts 3
The last alert() statement demonstrates how the end() method is used twice to remove
both the filter() and find() destructive changes, returning the wrapper set to its orig-
inal composition:
alert(jQuery('p').filter('.middle').find('span').end().end().length); //alerts 3
Discussion
If the end() method is used and there were no prior destructive operations performed,
an empty set is returned. A destructive operation is any operation that changes the
set of matched jQuery elements, which means any traversing or manipulation method
that returns a jQuery object, including add(), andSelf(), children(), closes(),
filter(), find(), map(), next(), nextAll(), not(), parent(), parents(), prev(),
prevAll(), siblings(), slice(), clone(), appendTo(), prependTo(), insertBefore(),
insertAfter(), and replaceAll().
1.8 IncludingthePreviousSelectionwiththeCurrentSelection
Problem
You have just manipulated a set of elements in order to acquire a new set of elements.
However, you want to operate on the prior set as well as the current set.
Solution
You can combine a prior selection of DOM elements with the current selection by using
the andSelf() method. For example, in the following code, we are first selecting all
<div> elements on the page. Next we manipulate this set of elements by finding all
<p> elements contained within the <div> elements. Now, in order to operate on both
the <div> and the <p> elements found within the <div>, we could include the <div> into
20 | Chapter 1: jQuery Basics
the current set by using andSelf(). Had I omitted the andSelf(), the border color would
have only been applied to the <p> elements:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<p>Paragraph</p>
<p>Paragraph</p>
</div>
<script type="text/JavaScript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery('div').find('p').andSelf().css('border','1px solid #993300');
</script>
</body>
</html>
Discussion
Keep in mind that when you use the andSelf() method, it will only add into the current
set being operated on and the prior set, but not all prior sets.
1.9 Traversing the DOM Based on Your Current Context to
Acquire a New Set of DOM Elements
Problem
You have selected a set of DOM elements, and based on the position of the selections
within the DOM tree structure, you want to traverse the DOM to acquire a new set of
elements to operate on.
Solution
jQuery provides a set of methods for traversing the DOM based on the context of the
currently selected DOM element(s).
For example, let’s examine the following HTML snippet:
<div>
<ul>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
<li><a href="#">link</a></li>
</ul>
</div>
1.9 Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements | 21
Now, let’s select the second <li> element using the :eq() index custom selector:
//selects the second element in the set of <li>'s by index, index starts at 0
jQuery('li:eq(1)');
We now have a context, a starting point within the HTML structure. Our starting point
is the second <li> element. From here we can go anywhere—well, almost anywhere.
Let’s see where we can go using a couple of the methods jQuery provides for traversing
the DOM. Read the comments in the code for clarification:
jQuery('li:eq(1)').next() //selects the third <li>
jQuery('li:eq(1)').prev() //selects the first <li>
jQuery('li:eq(1)').parent() //selects the <ul>
jQuery('li:eq(1)').parent().children() //selects all <li>s
jQuery('li:eq(1)').nextAll() //selects all the <li>s after the second <li>
jQuery('li:eq(1)').prevAll() //selects all the <li>s before the second <li>
Keep in mind that these traversing methods produce a new wrapper set, and to return
to the previous wrapper set, you can use end().
Discussion
The traversing methods shown thus far have demonstrated simple traverses. There are
two additional concepts that are important to know about traversing.
The first concept and likely most obvious is that traversing methods can be chained.
Let’s examine again the following jQuery statement from earlier:
jQuery('li:eq(1)').parent().children() //selects all <li>'s
Notice that I have traversed from the second <li> element to the parent <ul> element
and then again traversed from the parent element to selecting all the children elements
of the <ul> element. The jQuery wrapper set will now contain all the <li> elements
contained within the <ul>. Of course, this is a contrived example for the purpose of
demonstrating traversing methods. Had we really wanted a wrapper set of just <li>
elements, it would have been much simpler to select all the <li> elements from the
get-go (e.g., jQuery('li')).
The second concept that you need to keep in mind when dealing with the traversing
methods is that many of the methods will accept an optional parameter that can be
used to filter the selections. Let’s take our chained example again and look at how we
could change it so that only the last <li> element was selected. Keep in mind that this
is a contrived example for the purpose of demonstrating how a traversing method can
be passed an expression used for selecting a very specific element:
jQuery('li:eq(1)').parent().children(':last') //selects the last <li>
22 | Chapter 1: jQuery Basics
jQuery provides additional traversing methods that were not shown here. For a com-
plete list and documentation, have a look at http://docs.jquery.com/Traversing. You will
find these additional traversing methods used throughout this book.
1.10 Creating, Operating on, and Inserting DOM Elements
Problem
You want to create new DOM elements (or a single element) that are immediately
selected, operated on, and then injected into the DOM.
Solution
If you haven’t figured it out yet, the jQuery function is multifaceted in that this one
function performs differently depending upon the makeup of the parameter(s) you send
it. If you provide the function with a text string of raw HTML, it will create these
elements for you on the fly. For example, the following statement will create an <a>
element wrapped inside of a <p> element with a text node encapsulated inside of the
<p> and <a> elements:
jQuery('<p><a>jQuery</a></p>');
Now, with an element created, you can use jQuery methods to further operate on the
elements you just created. It’s as if you had selected the <p> element from the get-go in
an existing HTML document. For example, we could operate on the <a> by using
the .find() method to select the <a> element and then set one of its attributes. In the
case of the following code, we are setting the href attribute with a value of http://
www.jquery.com:
jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com');
This is great, right? Well, it’s about to get better because all we have done so far is create
elements on the fly and manipulate those elements in code. We have yet to actually
change the currently loaded DOM, so to speak. To do this, we’ll have to use the ma-
nipulation methods provided by jQuery. The following is our code in the context of an
HTML document. Here we are creating elements, operating on those elements, and
then inserting those elements into the DOM using the appendTo() manipulation
method:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
1.10 Creating, Operating on, and Inserting DOM Elements | 23
jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com')
.end().appendTo('body');
</script>
</body>
</html>
Notice how I am using the end() method here to undo the find() method so that when
I call the appendTo() method, it appends what was originally contained in the initial
wrapper set.
Discussion
In this recipe we’ve passed the jQuery function a string of raw HTML that is taken and
used to create DOM elements on the fly. It’s also possible to simply pass the jQuery
function a DOM object created by the DOM method createElement():
jQuery(document.createElement('p')).appendTo('body'); //adds an empty p element
to the page
Of course, this could be rather laborious depending upon the specifics of the usage
when a string of HTML containing multiple elements will work just fine.
It’s also worth mentioning here that we’ve only scratched the surface of the manipu-
lation methods by using the appendTo() method. In addition to the appendTo() method,
there are also the following manipulation methods:
• append()
• prepend()
• prependTo()
• after()
• before()
• insertAfter()
• insertBefore()
• wrap()
• wrapAll()
• wrapInner()
1.11 Removing DOM Elements
Problem
You want to remove elements from the DOM.
24 | Chapter 1: jQuery Basics
Solution
The remove() method can be used to remove a selected set of elements and their children
elements from the DOM. Examine the following code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h3>Anchors</h3>
<a href='#'>Anchor Element</a>
<a href='#'>Anchor Element</a>
<a href='#'>Anchor Element</a>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery('a').remove();
</script>
</body>
</html>
When the preceding code is loaded into a browser, the anchor elements will remain in
the page until the JavaScript is executed. Once the remove() method is used to remove
all anchor elements from the DOM, the page will visually contain only an <h3> element.
It’s also possible to pass the method an expression to filter the set of elements to be
removed. For example, our code could change to remove only anchors with a specific
class:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h3>Anchors</h3>
<a href='#' class='remove'>Anchor Element</a>
<a href='#'>Anchor Element</a>
<a href='#' class="remove">Anchor Element</a>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery('a').remove('.remove');
</script>
</body>
</html>
Discussion
When using the jQuery remove() method, you need to keep two things in mind:
1.11 Removing DOM Elements | 25
• While the elements selected are removed from the DOM using remove(), they have
not been removed from the jQuery wrapper set. That means in theory you could
continue operating on them and even add them back into the DOM if desired.
• This method will not only remove the elements from the DOM, but it will also
remove all event handlers and internally cached data that the elements removed
might have contained.
1.12 Replacing DOM Elements
Problem
You need to replace DOM nodes currently in the DOM with new DOM nodes.
Solution
Using the replaceWith() method, we can select a set of DOM elements for replacement.
In the following code example, we use the replaceWith() method to replace all <li>
elements with a class attribute of remove with a new DOM structure:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<ul>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
<li>name</li>
<li class='remove'>name</li>
</ul>
<script type="text/JavaScript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/JavaScript">
jQuery('li.remove').replaceWith('<li>removed</li>');
</script>
</body>
</html>
The new DOM structure added to the DOM is a string parameter passed into the
replaceWith() method. In our example, all the <li> elements, including children ele-
ments, are replaced with the new structure, <li>removed</li>.
26 | Chapter 1: jQuery Basics
Exploring the Variety of Random
Documents with Different Content
The National University of Havana was founded under the direction of
monks of the Dominican Order on January 5, 1728, and until the
installation of the Republic occupied the old convent that afterwards served
as the Institute. To-day the University of Havana can boast of one of the
most picturesque and delightful locations occupied by any seat of learning
in the world. It crowns the northeast corner of the high plateau, overlooking
the capital of the Republic from the west. Its altitude is several hundred feet
above the plain below, with the Gulf of Mexico close by on the north and
old Morro Castle standing at the entrance of a beautiful harbor, that
stretches out along the far eastern horizon, sweeping afterwards toward the
south. The city of Havana fills the center of the picture, while in the
immediate foreground nestle the forests of the Botanical Gardens and the
Quinto de los Molinos, or summer residence of the former Spanish
Governor Generals, with their beautiful drives sweeping along the front and
up to the crest of the plateau.
The broad stone staircase at the entrance to the grounds is quite in
keeping with the dignity of the place and the numerous buildings devoted to
various departments of learning are harmonious in design and commodious
in appointment. A giant laurel, with an expanse of shade that would protect
a small army of men, occupied the center of an old courtyard that once
belonged to the fortifications commanding the Principe Heights.
To these buildings will soon be added another to be known as the
National School of Languages, at a cost of $150,000. This edifice,
sumptuous in its appointments, will be dedicated largely to the reciprocal
study of Spanish and English. American students who wish to perfect their
knowledge of Spanish will be invited from the various universities of the
United States to visit Cuba, at stated periods of the year, for the purpose of
studying and improving their acquaintance with this language through
direct contact with the students and professors of the University. The latter,
on the other hand, will be afforded an excellent opportunity to perfect their
knowledge of English by mingling with visiting students from the United
States, and it is believed that the result of acquaintances and friendships,
formed in this way, many of which will be sustained through life, will add
greatly to those bonds of friendship and mutual understanding that resulted
from America’s assistance to Cuba in her War for Independence, and that
for a thousand reasons should never be permitted to relapse or sink into
indifference.
The national or public library of Cuba, located in the Maestranza, one of
the most substantial of those old buildings that have come down from the
days of Spanish dominion, was founded during the first American
intervention by General Leonard Wood, on October 18, 1901. It is open to
the public every day of the week except Sunday, from 8 to 11 in the
morning and from 1 to 5 in the afternoon, except Saturday, when access
may be secured at any time between 8 and 12 in the morning.
The library contains at the present time about twenty thousand volumes.
This does not however include a great mass of pamphlets and unbound
manuscripts, documents, papers, etc., which form a valuable part of the
collection. These volumes are largely in Spanish, French and English, and
include all of the more important branches of human knowledge. Among
them may be found an excellent collection of the best encyclopedias and
dictionaries of those languages.
Its collection of American History is extensive; in addition to which may
be mentioned a valuable collection of works on international law, given by
the eminent jurist Dr. Antonio S. de Bustamante, who represented the
Republic of Cuba at the Peace Conference in Paris at the conclusion of the
Great War.
Among other gifts to the public library may be mentioned a series of
large, beautiful, artistic drawings in colors, that represent all that is known
of the Aztec and Toltec life existing in the Republic of Mexico at the time
of the Spanish Conquest in the early part of the 16th century. These
engravings have been drawn and colored with marvelous care. They are
assembled in the form of an atlas which permits close study and makes one
of the most interesting and valuable contributions of this kind to be found in
any part of the world. They were presented to Cuba by General Porfirio
Diaz, President of the Republic of Mexico.
Arrangements have been made to catalogue the volumes of the library.
For this purpose experts have been secured and the space amplified, and
when this work is completed, while the library will not offer the luxurious
quarters of institutions of its kind in other countries, it will be useful and
accessible to those who wish to avail themselves of its services.
CHAPTER XXXV
OCEAN TRANSPORTATION
TRANSPORTATION is the handmaid of production. Where transportation
facilities are faulty, exchange of commodities is necessarily restricted to
local demands, and commerce with the outside world is practically
impossible. Good harbors are among the first essentials to foreign trade, and
with deep, well protected bays, Cuba has been bountifully supplied. Every
sheltered indentation of her two thousand miles of coast line, from the days
of Colon, has been an invitation for passing ships to enter. The wealth of the
island in agriculture and mineral and forest products, has made the visits of
these ocean carriers profitable; hence the phenomenal growth of Cuba’s
foreign commerce.
In spite of the stupid restriction of trade enforced by Spain in the early
colonial days, contraband commerce assumed large proportions during the
17th century, and when England’s fleet captured Havana in 1763, the capital
of Cuba enjoyed a freedom of foreign exchange never before known.
Quantities of sugar, coffee, hides and hardwoods, large for those times,
demanded transportation during the second quarter of the 19th century.
Foreign trade, too, was greatly stimulated in Cuba by conditions resulting
from the Civil War in the United States. The rapid development of the sugar
industry following this war soon called for more permanent lines of ocean
transportation.
THE CHAMBER OF COMMERCE, HAVANA
The Chamber of Commerce is one of the oldest
civic organizations in Cuba, which even under the
repressive and discouraging rule of Spanish Governors
did much for the material progress of the Island.
Under the Republic its activities and achievements
have of course been immensely increased, and it is
now appropriately housed in one of the finest public
buildings of the capital. A certain resemblance to the
famous Cooper Union building in New York has often
been remarked, though the Havana edifice is the more
ornate and attractive of the two.
The interdependence of produce and transportation is well illustrated in
the early history of what is now known as the United Fruit Company. In
1870, Captain Lorenzo D. Baker was in command of a small, swift coasting
schooner en route from Jamaica to Boston. On the wharf at Kingston lay
some 40 bunches of bananas, a few of which were ripe, others lacking 10
days or more in which to change their dull green coats into the soft creamy
yellow of the matured fruit. Captain Baker was fond of bananas, and
ordered that the lot be placed on board his schooner, just before sailing.
Fortune favored him and strong easterly beam winds brought him into the
harbor of Boston in 10 days, with all of the bunches not consumed en route
in practically perfect condition. Many friends of Capt. Baker, to whom this
delicious fruit was practically unknown, got a taste of the banana for the
first time. Among these was Andrew W. Preston, a local fruit dealer in
Boston, who was greatly impressed with the appearance of the fruit, and the
success which had attended Captain Baker’s effort to get the bananas into
the market without injury.
Mr. Preston reckoned that if a schooner with a fair wind could land such
delicious fruit in Boston in ten days, steamers could do the same work with
absolute certainty in less time. This far sighted pioneer and promoter of
trade realized that three factors were essential to building up an industry of
this kind. First, there must be a market for the product, and he was
confident that the people of Boston and the vicinity could soon be educated
to like the banana and to purchase it if offered at a fair price. Next, a
sufficient and steady supply must be provided. Third, reliable transportation
in the form of steamers of convenient size and suitable equipment must be
secured, in order to convey the fruit with economy and regularity to the
waiting market or point of consumption. True, he at first failed to interest
other fruit dealers in the project. “It had never been done and consequently
was a dangerous innovation that would probably prove unprofitable.” But
Mr. Preston had visualized a new industry on a large scale, and with the
faith of the industrial pioneer he finally succeeded in persuading nine of his
friends to put up with him each $2,000, and to form a company for the
purpose of growing bananas in the West Indies, of chartering a steamer
suitable for the transportation, and finding a market for the produce in
Boston.
The details were worked out carefully and the first cargo purchased in
Jamaica and landed in New England proved a decided success. During the
first two or three years the accruing dividends were invested in fruit lands in
Jamaica and everything went well. Not long after, however, it was found
that a West Indian cyclone could destroy a banana field and put it out of
business in a very few hours. More than one field or locality in which to
grow bananas on a large scale was necessary to provide against the possible
failure of the crop at some other point.
In the meantime another broad minded and determined pioneer in the
world of progress, Minor C. Keith, a youth of 23, was trying to build a
railroad some 90 miles in length from Puerto Limon to the capital, San Jose,
in the highlands of Costa Rica. The greater part of this road was through
dense jungle and forest almost impenetrable, with nothing in the shape of
freight or passengers from which revenues could be derived until the road
was completed to the capital. Mr. Keith had a concession from the Costa
Rican Government, but the Government had no funds with which to aid the
builder in his enterprise, and this young engineer, through force of character
and moral suasion, kept his two thousand workmen in line without one
dollar of money for over 18 months. Food he managed to scrape up from
various sources, but the payday was practically forgotten. In the meantime,
some banana plants were secured from a plantation in Colombia, and set out
on the virgin soils along the roadway through which Mr. Keith was laying
his rails. These grew marvellously, and not only supplied fruit for the
Jamaica negroes engaged in the work, but soon furnished bananas for
export to New Orleans, and thus was started a rival industry to that of Mr.
Preston, on the shores of the Western Caribbean.
It was not long before Mr. Keith, who struggled for 20 years to complete
his line from the coast to the capital of Costa Rica, came into contact with
Mr. Preston. These captains of industry realized the advantages of co-
operation, and in a very short time organized the United Fruit Company,
which is probably the greatest agricultural transportation company in the
world to-day. Its various plantations include lands in Colombia, Panama,
Costa Rica, Honduras, Guatemala and Jamaica. Large plantations of
bananas belonging to the company were until recently on the harbors of
Banes and Nipe, on the north coast of Oriente, in the Island of Cuba, but
these were subjected to strong breezes from the northeast that whipped the
leaves and hindered their growth. Then too, it was soon discovered that
these lands were better adapted to the cultivation of sugar cane, hence
bananas of the United Fruit Company disappeared from the Nipe Bay
district, to be replaced by sugar plantations that to-day cover approximately
37,000 acres and in 1920 will reach 50,000 acres. Over 200,000 acres on
the coast of the Caribbean are devoted to the cultivation of bananas. About
30,000 head of cattle are maintained as a source of food for the thousands
of laborers, mostly Jamaicans, who are employed in the fields of the United
Fruit Company, which comprise an aggregate of 1,980,000 acres; while 743
miles of standard gauge railway, together with 532 miles of narrow gauge
roads, are owned and operated throughout the various plantations.
In the year 1915, 46,000,000 bunches of bananas were shipped by the
United Fruit Company from the shores of the Caribbean to the United
States, while the sugar plantations owned by the Company on the north
coast of Oriente Province, in Cuba, produced sugar in 1918 that yielded a
net return of $5,000,000.
In order to provide transportation for this enormous agricultural output
this company to-day owns and operates one of the biggest fleets of
steamships in the world. Forty-five of these ships, with tonnages varying
from 3,000 to 8,000, especially equipped for the banana trade, and with the
best of accommodations for passengers, have an aggregate tonnage of
250,000; while 49 other steamers were chartered by the company before the
war, making the total tonnage employed in the carrying trade approximately
half a million.
Nearly all these steamers, which connect the coast of the Caribbean with
New York, Boston and New Orleans, touch, both coming and going, at the
City of Havana, thus giving that port the advantage of unexcelled
transportation facilities, and connecting Cuba not only with the more
important cities of the Gulf of Mexico, New York and New England, but
also with Jamaica, Caribbean ports, and the South American Republics
lying beyond the Isthmus of Panama, along the western shores of that
continent.
No steamship line perhaps has been more closely related to the
commercial development of Cuba than has the New York & Cuba Mail
Steamship Company. This line had its origin in a carrying trade between
Cuba and the United States started by the firm of James E. Ward & Co. The
members of the firm were Mr. James E. Ward, Mr. Henry B. Booth and Mr.
Wm. T. Hughes. The Company was incorporated under the laws of the State
of New York and formally organized in July, 1881, with Mr. Ward as
President, Mr. Booth as Vice President and Mr. Hughes as Secretary and
Treasurer. When first organized the Company had only four ships, the
Newport, Saratoga, Niagara and Santiago, with a gross tonnage of 10,179.
Between the date of its organization and its transfer to the Maine
Corporation, or during a period of 26 years, the company acquired 19
vessels, with a total gross tonnage of 84,411. In addition to the above the
company has operated under foreign flags eight other ships aggregating a
tonnage of 26,624.
The four original steamers mentioned above were owned in part by the
builders, Messrs. John Roach & Son, and a few other individuals. The
original firm however sold its ships to the Company at the time of its
reorganization. Of the vessels acquired by the company, the majority were
built under contract by Messrs. Roach & Son, and Wm. Cramp & Sons’
Ship and Engine Building Company. Among the ships that were purchased
and not built especially for this company, were the two sister ships
Seguranca and Vigilancia, built in 1890 for the Brazil Line. The steamships
City of Washington and City of Alexandria were originally owned by the
Alexandria Line, and passed into the hands of the Ward Line after its
organization. The Matanzas, formerly the Spanish steamer Guido, that had
left London with a valuable cargo of food, munitions and money with
which to pay off Spanish troops in Cuba, was captured by the American
forces during the early part of the war with Spain, in an attempt to run the
blockade that had been established, and was afterwards sold by the
American Government to the Ward Line.
The business of this company, after its organization, began with a
passenger and freight service connecting the cities of Havana, Santiago and
Cienfuegos with New York. With the acquisition of the Alexandria Line, the
service of the company was extended to Mexico, and a number of ports
have been added to its itinerary both in Cuba and in Mexico. The line to-
day maintains a service on each of the following routes: New York to
Havana and return; New York to Havana, Progreso, Yucatan, and Vera Cruz,
returning via Progreso and Havana to New York; New York to Tampico,
Mexico, calling occasionally on return voyages at other ports when cargoes
are offered; New York to Guantanamo, Santiago, Manzanillo and
Cienfuegos, returning according to the demands of shipping interests; New
York to Nassau, in the Bahamas, Havana, and return. The sailings average
about five a week and schedules are prepared from time to time to meet the
requirements of trade. Passengers on this line are carried in three distinct
classes, first cabin, intermediate, and steerage, the vessels being constructed
with reference to suitable accommodations for the various classes.
The principal railway and other connections are as follows: At New York
in general with all railroads terminating at that port, as well as all foreign
and domestic water lines that move traffic via that port; at Havana with the
United Railways of Havana and the Cuba Railroad; at Tampico with the
Mexican Central Railway for interior points in Mexico; at Progreso with the
United Railways of Yucatan for Merida, Campeche and other interior
points; at Vera Cruz with the National Railways of Mexico and the
Interoceanic Railroad for interior points of Mexico, as well as with the Vera
Cruz and Pacific Railroad for interior points of Mexico and the Pacific
Coast; at Puerto Mexico with the Tehuantepec National Railway, for points
on the Isthmus of Tehuantepec and on the Pacific Coast. Connection is also
made at Vera Cruz with the Compañia Mexicana de Navegacion for traffic
to Tuxpam, Coatzacoalcos, Tlacotalpam and Frontera, ports on the Gulf of
Mexico. At Santiago connection is made with the Cuba Eastern Railway
and Cuba Railroad for points throughout the interior of Cuba; at
Guantanamo with the Cuba Eastern Railway and at Cienfuegos with the
Cuban Central Railroad.
The company has contracts with the United States Government for the
transportation of mails between New York and Havana, and between New
York, Havana and Mexico. It also has a contract with the Bahamas
Government for the transportation of mails.
The following is a list of the vessels owned or operated by the company.
Steamers:
Havana Matanzas
Saratoga Antilla
Mexico Camaguey
Morro Castle Santiago
Esperanza Bayamo
Monterey Manzanillo
Segurancia Yumuri
Vigilancia Guantanamo
Seneca
Tugs and Steam Lighters:
Colonia Auxiliar
Nautilus Comport
Neptuno Edwin Brandon
Hercules
The total gross tonnage of the steamers and tugs above mentioned is
84,000 tons.
One of the oldest and most important lines in the carrying trade of the
Caribbean is known as the Munson Steamship Line, and was founded in
1872 by Walter D. Munson. The trade began with sailing vessels but the
increase in traffic was so great that these were soon replaced with steamers.
The steamships in the service of the Munson Line to-day number 140, with
an average tonnage of 2,500 tons each, dead weight.
These vessels sail from nearly every port in Cuba, connecting the Island
with nearly all of the Atlantic and Gulf Coast ports of the United States. The
passenger steamers of the Munson Line ply between New York, Nuevitas
and Nipe Bay of the Province of Oriente. The passenger steamers, although
not touching at Havana, are equipped for the accommodation of passengers
that leave from the ports of the eastern provinces of the Island.
During the late European War twelve of the Munson steamships were
placed in the service of the United States and three under the British flag.
The Peninsular and Occidental Steamship Company operates a daily
passenger, mail and freight service between Havana and Key West, Florida.
Since 1912 this company has maintained practically a daily service between
the two ports and maintains also a bi-weekly service between Havana and
Port Tampa, Florida. Owing to the frequency of the sailings, the P. & O. SS.
Co. is considered the official mail route between the United States and
Cuba.
The company operates also the Florida East Coast Car-Ferry freight
service between Havana and Key West. This service was made possible by
the extension of the Florida East Coast Railroad from the southern points of
the peninsula out over the long line of keys that terminates in the Island of
Key West.
The erection of this viaduct, built at an enormous expense, of stone and
concrete, was the realization of Henry W. Flagler’s dream of modern
transportation facilities between the United States and Cuba. The car ferry
service was inaugurated in January, 1915. At the present time two of these
great car ferryboats, with a capacity of 28 standard freight cars each, make a
round trip every twenty-four hours between the two ports. These two
vessels transport approximately 1,150 cars in and out of Cuba every month,
carrying over 35,000 tons each way in that length of time.
Since the inauguration of the service more business has been offered
than can be handled during certain months of the year, and it has been found
necessary to refuse large quantities of cargo destined for the Republic of
Cuba. The advantage of this service to the Cuban fruit and vegetable
growers has been very great, since they are enabled to load in the Cuban
fields freight cars belonging to almost every line in the United States, so
that this produce may be shipped direct, without breaking bulk, to any
market in the United States.
In the year 1870 the Pinillos Izquierdo Line of steamers was established
between Spain and the Island of Cuba. The home office of this line is in
Cadiz, Spain. Their vessels are engaged in freight and passenger service
touching at the following points in the Peninsula: Barcelona, Palma de
Majorca, Valencia, Alicante, Malaga, Cadiz, Vigo, Gijon and Santander.
En route the Canary Island and Porto Rico are also visited while the
terminal points on this side of the Atlantic are New Orleans, Galveston,
Havana and Santiago de Cuba. All of their steamers carry mail. Their fleet
consists of nine steamers with a combined tonnage of 78,000 tons as
follows:
Infanta Isabel 16,500 tons2000 passengers
Cadiz 10,500 tons1500 passengers
Barcelona 10,500 tons1500 passengers
Valbanera 10,500 tons1500 passengers
Catalina 8,000 tons1000 passengers
Martin Sáena 5,500 tons 800 passengers
Balmes 6,500 tons 800 passengers
Conde Wifredo 5,500 tons 800 passengers
Miguel M. Pinillos 4,500 tons 500 passengers
78,000 tons
The Southern Pacific, originally known as the Morgan line, established a
transportation service between Gulf ports and the Island of Cuba many
years ago, beginning with two side-wheel walking-beam steamboats of
about 800 tons dead weight. They were heavy consumers of coal and had a
speed of from 9½ to 11 knots. A few years later the steamers Hutchinson
and Arkansas, both side wheelers, were added to the fleet. Still later the
single propeller steamers Excelsior and Chalmette, of about 2,400 tons
each, were placed in the service of the Southern Pacific Line. These
combined freight and passenger boats were well built and seaworthy
fourteen knot steamers, of an equipment considered modern at that time.
The Louisiana entered the service in 1900, but owing to an error in loading
freight, it turned turtle at the docks in New Orleans and became a total loss.
The Excelsior and Chalmette are still maintaining an efficient weekly
service between New Orleans and Havana.
The Compagnie General Transatlantique, generally known as the French
Line, connecting western France, Northern Spain and the Canary Islands,
with Cuba, Porto Rico, Vera Cruz, Mexico, and the city of New Orleans,
was established in 1860.
St. Nazaire on the Bay of Biscay in France is the headquarters of this
line. Their steamers touch at Santander and Coruña on the north coast of
Spain; at the Canary Islands, Porto Rico, Martinique, Santiago de Cuba,
Havana, Vera Cruz, and New Orleans. Their fleet consists of 13 ships with a
combined tonnage of 153,500 tons.
The steamship Lafayette, of 15,000 tons, is equipped for the
accommodation of 1,620 passengers. The Espana, of 15,000 tons, carries
1,500 passengers; the Flanders, of 12,000 tons, carries 1,250 passengers;
the Venizia, of 12,000 tons, carries 700 passengers; the Navarre, of 10,000
tons, carries 1,000 passengers; the Venezuela, of 7,000 tons, carries 500
passengers.
The Caroline, the Mississippi and the Georgie are each steamers of
13,000 tons. The Honduras is a 12,000 ton ship; the Hudson 11,000 tons;
the Californie 10,500 tons, and the Virginie 10,000 tons. The seven last
mentioned vessels carry cargo only.
During August, 1919, the 7,000 ton steamer Panama Canal arrived in
Cuba from Japan, inaugurating a new steamship line between Japan and the
United States, touching at Cuban ports. The line is known as the Osaka
Shosen Kaisha, of Osaka, Japan. The fleet consists of 186 steamers plying
between Japan and different parts of the world. The headquarters for this
company has been established at Chicago, Illinois, owing to connections
that have been made with the Chicago, Milwaukee and St. Paul Railroad.
Steamers eastward bound from Japan will bring rice and general cargo,
most of which will be consigned to the Island of Cuba, owing to the heavy
consumption of that article of food in that Republic. New Orleans will be
the terminus in the United States of the line. On the initial trip of the
Panama Canal 50,000 sacks of rice grown in Japan were consigned to
Cuban merchants in Santiago de Cuba and Cienfuegos. The return cargoes
will be composed largely of cotton, taken aboard at New Orleans, and with
sugar and tobacco shipped from Cuba to the Orient. This line has begun
with one sailing each way per month, all steamers touching at Havana for
freight and passengers.
The Customs regulations of Cuba require five sets of invoices for
Havana and four for all other points; which must be written in ink, in either
English or Spanish. If they are typewritten the original imprint must be
included, but the others may be carbon copies. Invoices must give the
names of shippers and consignees, and of vessels; marks and numbers,
description of merchandise, gross and net weights by metric system, price,
value, and statement of expenses incurred. If there are no expenses, that fact
must be stated. Prices must be detailed, on each article, and not in bulk.
Descriptions of merchandise must be detailed, telling the materials of each
article and of all its parts. Descriptions of fabrics must tell the nature of the
fibre, character of weave, dye, number of threads in six square millimeters,
length and width of piece, weight, price, and value. All measurements must
be in metric units.
At the foot of each sheet of the invoice must be a signed declaration, in
Spanish, telling whether the articles are or are not products of the soil or
industry of the United States. If the manufacturer or shipper is not a resident
of the place where the consulate is situated, he must appoint in writing a
local agent to present the invoice and the agent must write and sign a
declaration concerning his appointment. Stated forms are prescribed and are
furnished by consuls for manufacturers, producers, owners, sellers and
shippers.
Freight charges to the shipping port, custom house and statistical fees,
stamps, wharfage and incidental expenses must be included in the dutiable
value of goods, and must be stated separately; but insurance and consular
fees must not be included.
Each invoice must cover a single, distinct shipment, by one vessel to one
consignee. Separate consignments must not be included in one invoice.
Invoices under $5, covering products of the soil or industry of the United
States must be certified in order to enjoy the provisions of the reciprocity
treaty between the two countries. Invoices and declarations must be written
on only one side of the paper, and no erasures, corrections, alterations or
additions must be made, unless stated in a signed declaration.
Domestic and foreign merchandise from the United States must be
separately invoiced. Invoices are not required on shipments of foreign
goods of less value than $5.
Fabrics of mixed fibres must be so stated, with a statement of the
proportion of the principal material, upon which the duty is to be computed.
Cotton goods pay duty according to threads, and silk and wool ad valorem.
Samples of cotton goods are taken at the custom house, and should be
provided for that purpose to avoid mutilation of the piece. Duties on ready
made clothing are based on the chief outside fabric. A surtax of 100% is
placed on ready-made cotton clothing, and a surtax of 30% on colored
threads.
Two copies of each set of bills of lading must be given, but on
merchandise of less than $5 value need not be certified.
Invoices covering shipments of automobile vehicles must state maker,
name of car, style of car, year of make, maker’s number on motor, number
of cylinders, horse power, and passenger capacity.
If after an invoice has been certified it or any part of it is delayed in
shipment, the steamship company must mark on the bill of lading opposite
the delayed goods “Short Shipped,” but the invoice need not be recertified.
The consignee should, however, be informed.
The list of articles admitted into Cuba free of duty comprises samples of
fabrics, felt, and wall paper, of a prescribed size, samples of lace and
trimmings, and samples of hosiery, provided that they are rendered unfit for
any other purpose than that of samples; trained animals, animals, portable
theatres, and other articles for public entertainment, not to remain in Cuba
longer than three months; receptacles in which fruits or liquids were
exported from Cuba and which are being returned empty; furniture, clothing
and other personal property of immigrants, or of travellers, showing
evidence of having already been used; agricultural implements not
including machinery; and pictures, posters, catalogues, calendars, etc., not
for sale but for free distribution for advertising purposes.
The importation into Cuba is forbidden or restricted of foreign coins of
anything but gold, save those of the United States; gunpowder, dynamite
and other explosives, save by special permit of the Interior Department; and
silencers for firearms. Arms of more than .32 caliber, .44 caliber revolvers,
and automatic pistols require special permit.
Consular fees for certification are: On shipments worth less than $5,
nothing; from $5 upward and less than $50, fifty cents; from $50 upward
and less than $200, $2; over $200, $2 plus ten cents for each $100 or
fraction thereof. Extra copies of invoices, 50 cents each. Invoice blanks, ten
cents a set. Certifying bills of lading, $1.
Cuban consulates are situated in the United States and its possessions as
follows: Atlanta, Ga.; Baltimore, Md.; Boston, Mass.; Brunswick, Ga.;
Chattanooga, Tenn.; Chicago, Ill.; Cincinnati, Ohio.; Detroit, Mich.;
Fernandina, Fla.; Galveston, Tex.; Gulfport, Miss.; Jacksonville, Fla.;
Kansas City, Mo.; Key West, Fla.; Los Angeles, Cal.; Louisville, Ky.;
Mobile, Ala.; New Orleans, La.; New York; Newport News, Va.; Norfolk,
Va.; Pascagoula, Miss.; Pensacola, Fla.; Philadelphia, Penn.; San Francisco,
Cal.; Savannah, Ga.; St. Louis, Mo.; Tampa, Fla.; Washington, D. C.; and
Aguadilla, Arecibo, Mayagues, Ponce, and San Juan, Porto Rico.
CHAPTER XXXVI
AMERICAN COLONIES IN CUBA
AMERICAN soldiers returning to the United States at the conclusion of her
little war with Spain, in the summer of 1898, brought wonderful stories of
Cuba, with glowing accounts of her climate, her rainfall, her rich soil and
natural advantages. Schemes for the colonization of the Island were
immediately formed and some of them put into effect during the early days
of the Government of Intervention.
Unfortunately, most of these enterprises originated with speculators, and
so-called land-sharks, who sought only to secure large tracts of territory, at
the smallest possible cost, and with the assistance of attractive literature
place them on the market in the United States, at prices which would enable
them, even when sold on the installment plan to make a thousand percent or
more profit on the capital invested.
This method of settling up the country would not have been so
objectionable had the promoters of the schemes taken the pains to locate
their colonies in those sections of the Island where transportation facilities,
if not immediately available, could at least be reasonably sure in the near
future.
Up to the present, a logical, common sense plan in the colonization in
this Island has in no instance been carried out. On the contrary, every
American colony that has yet been established in Cuba, and her adjacent
Islands, has been located with disregard to the first essentials of success.
These hapless experiments have met with a fate that was inevitable and in
most instances can be described with one word “Failure.”
The first American Colony in Cuba was started on Broadway, New York
City, by a land speculator, who, through correspondence, learned of a large
property that could be had in Cuba with a small cash payment, at what
seemed to be a ridiculously low price; in other words at about 80 cents an
acre. An option was secured on several thousand acres, the larger part of
which, perhaps, was available for general agricultural purposes. But the
location with reference to transportation facilities was one of the most
unfortunate that could have been selected. This colony was called La
Gloria, and while La Gloria has not been a failure, nothing in the world has
saved it but the pluck, and persistent and intelligent effort of a courageous
and most commendable community of Americans.
Some 800 of these, not knowing where they were going, other than that
it was somewhere in Cuba, were dumped by a chartered steamer in the
harbor of Nuevitas, 40 miles from their destination. This they afterwards
reached with the aid of light draft schooners, or shallow, flat-bottom boats,
pushed through a muddy ditch some three or four miles, and as many more
over sand shoals, where the passengers were compelled to get out and
wade. Worse than all, when finally landed on the south shore of Guajaba
Bay, they were obliged to wade through a swamp for another five miles, in
mud knee-deep, or more, in order to reach the high ground on which they
were to make their future homes in a foreign land.
Many of these colonists, disappointed and deceived, failed to stand the
strain, and those who had the necessary funds, or could borrow, returned
disgusted to their homes in the United States. Others, after studying the soil
and noting the splendid growth of forest and vegetation, lulled into
resignation by soft, cool breezes from the Atlantic Ocean, and the bright
sunshine that seldom missed a day, made up their minds to stick to the game
and to see it out, which they did.
Their efforts in the end were crowned with a certain degree of success,
and the near future holds out to them the promise of fairly satisfactory
transportation for their fruit, vegetables and other products, to profitable
markets, both in Cuba and the United States.
The colony of La Gloria in the fall of 1918 contained about 75 families
and comprised, all told, probably 500 people. This estimate includes the
little nearby settlements of Guanaja, Punta Pelota, Columbia, Canasi, The
Garden, and other little suburbs or groups of families, scattered throughout
the district.
With the Cubans, the people of La Gloria have always maintained the
most friendly relations, while mutual esteem and respect is the rule of the
district. The Mayor of La Gloria, a Cuban, was elected by popular vote, and
is highly esteemed in the community as a man who has been always an
enthusiastic and efficient supporter of the interests of the colony. Seventy
per cent of the population is American. La Gloria has always been fortunate
in having a good school in which both Spanish and English are taught.
The town itself is located on the northern edge of the plateau, or rise of
ground overlooking the savanna that separates it from the bay. A fairly good
road some five miles in length, built at Government expense, connects the
town with the wharf, whence, up to the winter of 1918, all produce was sent
for shipment to the harbor of Nuevitas some forty miles east by launch.
The streets are very wide, shaded with beautiful flowering flamboyans,
and the houses, many of them two stories in height, are built of native
woods, cedar, mahogany, etc., products of the saw mills of the
neighborhood. These, as a rule, are kept painted, and the general appearance
of the town, although not bustling with business, is one of comfort,
cleanliness and thrift.
It is not an exaggeration to state that there is no little town in
conservative New England where less of waste, or disfiguring material,
even in back yards, or rear of houses, can be found, than in the little town of
La Gloria. The furnishing of most of the houses consists of a strange
mingling of articles of comfort brought from home, combined with other
things that have been improvised and dug out of their tropical surroundings.
A mistake, made in the early days of La Gloria, and one common to
every American colony in the West Indies, has been the exclusive
dedication of energy, effort and capital to the growth of citrus fruit. The first
essential factor to the success of a colony in any climate is food, and forage
for animals. This, in nearly every American town in Cuba, has been
ignored, every effort being expended on the planting and promotion of a
citrus grove from which no yield could be expected inside of five or six
years, and during which time, many a well meaning farmer has become
discouraged or has exhausted his capital, leaving his grove in the end to be
choked up with weeds and ruined by the various enemies of the citrus
family. However, the people of La Gloria planted and stuck to their orange
trees and many of these, today, are yielding very satisfactory returns, in
spite of the serious lack of transportation.
The best land belonging to the colony is located in the district known as
Canasi, some three miles south of the town, in the direction of the Cubitas
Mountains. There are 600 acres in this section devoted to oranges and grape
fruit, all of which have been well cared for and are increasing in value each
year.
The citizens of the colony have joined forces and built a well equipped
packing plant, 100 feet in length by 30 feet in width, from which, last year,
were shipped 432,000 loose oranges, and 9,200 boxes of grape fruit, the
latter going to the United States by the way of Nuevitas. All of this fruit at
the present time is hauled by wagon, some eight or nine miles to the wharf,
on the bay, whence it is conveyed to the harbor of Nuevitas for sale and
shipment.
La Gloria’s hope of really satisfactory transportation facilities is vested
in the North Shore Railroad of Cuba, and her dream of suitable connections
with the outside world of trade will soon be realized. La Gloria has many
things to commend it, aside from soil and climate. One of these is excellent
drinking water, found at an average depth of twenty feet. The soil on which
the town is built is largely impregnated with iron ore, which forms a
splendid roadbed, and enables the population to escape the seas of mud that
are rather common throughout the interior, excepting along macadamized
roads.
Most vegetables, with the exception of potatoes, may be grown
throughout the entire year in La Gloria, and a variety of potato adapted to
that peculiar soil will probably be found in the near future. A serious
mistake common not only in La Gloria but in nearly all other colonies in
Cuba has been neglect in sowing forage plants and thus providing for live
stock, so essential to the success of any farming district.
That which is most to be admired in La Gloria, is the class of people
who form the backbone of the colony, and who certainly came from
excellent stock, proved by their successful efforts in overcoming difficulties
that would have discouraged a less persevering community. The colony
supports a weekly newspaper, and holds annual agricultural fairs that are a
credit to the district.
The second and most serious experiment in colonization in Cuba was
staged in the Isle of Pines. In the year 1900 this intrepid storm sentinel of
the Caribbean offered several advantages for a successful exploitation of the
American public. In spite of the fact that this Island had always formed an
integral part of Cuba, it was advertised throughout the United States as
American property, and the flag raised by the Government of Intervention
was pointed to as a permanent asset of that particular section.
Again the promoters of this pretentious colonization scheme absolutely
ignored the basic principles of success in colony work. In other words they
did not take into account that not only was the Isle of Pines devoid of a
first-class harbor, but that the chances of securing direct transportation
between that section and the United States was decidedly remote.
Through the hypnotic influence of beautifully worded advertisements
and attractive pictures, large numbers of settlers from the United States and
Canada, especially from Minnesota and the Dakotas, were tempted to locate
in the Isle of Pines, or to purchase property, usually on the installment plan,
which they had never seen, and for which they paid exorbitant prices.
Tracts that cost from 90¢ to $1.20 per acre, were divided into 10, 20 and
40 acre farms, and sold at prices ranging from $25 in the beginning up to
$75 and even $100 per acre in 1918. These prices have always been out of
proportion to the quality of the soil, and the location of the land, since lands
far more fertile, and within easy reach of steamers leaving Havana daily,
might have been found on the mainland of Cuba, that would give the
prospect of a fair chance of success in almost any agricultural undertaking.
Here again the prospective settler was advised to start citrus fruit groves,
to the exclusion of forage and other crops from which immediate returns
would have encouraged the farmer, and permitted him to live economically
while making up his mind as to the advisability of citrus fruit culture, which
is a specialized form of horticulture, requiring much technical knowledge,
and a great deal of experience to insure satisfactory results.
In the Isle of Pines, as in La Gloria, while many men have been
disappointed, and many families have left the country in despair, there still
remains a nucleus of hard working, intelligent and enterprising men who, in
spite of the disadvantages that will surround them, have made for
themselves comfortable homes, and who enjoy the quiet, dreamy life that
soon becomes essential to the man who remains long in the tropics.
The Isle of Pines ships a considerable amount of fruit and vegetables
each year, through Havana, to markets in the United States. How often the
balance may be found on the profit side of the ledger, however, is open to
question. The Isle of Pines undoubtedly offers an excellent retreat for those
who have become tired of the strenuous life of cities, and who prefer to pass
the remainder of their days in pleasant, healthful surroundings. To do this,
of course, requires an income that will insure them against any little petty
annoyance that might come from a disturbing cyclone, or a low price for
grape fruit in northern markets.
The enterprising promoters connected with the early colonization of the
Isle of Pines made a second experiment at Herradura, in the Province of
Pinar del Rio, 90 miles from the city of Havana by rail. Here they
purchased some 22,000 acres of land in 1902, paying, it is said, an average
price of a dollar an acre, and started the third American colony in Cuba
under the name of Herradura.
In the colonization work, the old La Gloria and Isle of Pines method of
advertising was faithfully followed, and with results eminently satisfactory
to the promoters, most of whom have acquired comfortable fortunes, at the
expense of Americans and Canadians in the United States who were
anxious to find homes where they could enjoy life and perhaps prosper in
the Tropics.
The larger part of the Herradura tract, especially that which lay along the
Western Railroad, was a light sandy soil, used by the natives in the olden
days for grazing cattle, and burned over every winter, thus destroying nearly
all of the humus in the land. This property was divided into 40-acre tracts
and sold at $20 per acre. As soon as the settlers from the United States
began to arrive in any numbers, the price was advanced to $40. Citrus fruit
was held out to prospective home seekers as the surest means of securing an
easy life and a fortune after the first four or five years.
Under favorable conditions, where all the essential elements to success
are combined, this is possible. But Herradura did not combine all of the
required features, hence hundreds of acres of abandoned groves can be seen
along the railroad track for miles, as one enters the Herradura district. The
cyclone of 1917 which added the last straw to the proverbial camel’s back,
in the Isle of Pines, swept across the western end of Pinar del Rio Province
also, and only those groves that had been provided with wind-breaks
escaped from blight and ruin in the hurricane.
Today there are about 25 families, with perhaps 100 inhabitants,
remaining in the colony of Herradura. Some of these settlers, men of
experience, who came from the citrus grove districts of Florida, and others
who took up general farming on the better lands, some two or three miles
north of the railroad, have succeeded, and have built for themselves
comfortable homes where rural life is enjoyed to the utmost.
Some of them have their machines with which they can motor over a
splendid automobile drive to Havana, and spend a few days in the capital,
during the opera season. Nearly all of them have a few saddle horses that
furnish splendid exercise and amusement for the younger members of the
colony. One of the successful old timers of Herradura is Mr. Earle, formerly
chief of the Government Experimental Station at Santiago de Las Vegas, a
scientific farmer and a good business man. Mr. Earle located on good land
in a little valley well back from the road, planted 40 acres in citrus fruit and
has succeeded where others failed.
On all lands where irrigation is possible, the growing of vegetables,
especially peppers and egg plants, has proven very satisfactory. The average
number of crates per acre is 350, and a dollar per crate net is the estimated
average profit. The irrigation comes either from wells or little streams.
The raising of pigs and poultry has helped greatly all those farmers of
Herradura who had the foresight not to neglect the live stock and poultry
end in their farming enterprises.
The price of fairly good land in Herradura today is from $25 to $50 per
acre. The successful owner of a well cared for citrus grove in this colony
values it at $1,500 per acre. The freight on fruit and vegetables from
Herradura to the city of Havana over the Western Road, is ten cents per box.
The colony boasts of a very comfortable school house, which also serves
as a church and town hall. The old standbys, as they call themselves,
seldom complain of their lot, and could hardly be induced to change or seek
homes in other localities.
There are some half dozen American and Canadian colonies in the
Province of Oriente, most of them scattered along the line of the Cuba
Company’s railroad that has brought the interior of that province into
contact with the seaports of Antilla, on the north coast, and Santiago de
Cuba on the south. The colony of Bartle is the westernmost, located about
fifty miles from the borderline between that province and Oriente.
The Bartle tract consisted originally of 5,000 acres, 3,000 of which lie
north of the railroad and the remainder extending toward the south. Most of
the land is covered with a heavy forest of hard woods and the work of
clearing is a serious proposition, although the soil, once freed from stumps,
is exceptionally rich and productive. Less than 2,000 acres have been
cleared up to the present, and some three or four hundred have been planted
in citrus fruit. Good water is found at a depth of 25 feet.
There are approximately 200 permanent residents in this little settlement,
which has been laid out to advantage with its Plantation House, hotel,
church, stores, etc., and a very neat railway station. The buildings are nearly
all frame, painted white with green trimmings. In Bartle, as in all colonial
settlements in Cuba up to the present, the planting of citrus fruit seems to
have been the aim and ambition of the settlers, who are about evenly
divided between Canadians and Americans.
Just south of Bartle are a number of small estates on land that belonged
to the late Sir Wm. Van Horne, father of the Cuba Company Railroad.
Twenty miles further east a colony has been established at Victoria de las
Tunas, one of the storm centers of the various revolutionary movements on
the part of the Cubans against Spanish control. There are some 800 or 900
acres of citrus fruit groves, in various stages of production, within a radius
of fifteen miles surrounding the town of Victoria de las Tunas. In nearly all
of the American and Canadian colonies in the Province of Oriente, settlers
have learned, at times through bitter experience, that it was an economical
mistake to devote all of their energies to the production of citrus groves that
could give them no returns inside of five years, and that, with the exception
of the local markets of Camaguey, Manzanillo and Santiago de Cuba,
neither oranges nor lemons would bring a sufficient price to pay for the cost
of packing, transportation and sale. Grape fruit usually yielded a profit, if
the market happened to be just right; or in other words, if competing
shipments from Florida and California did not lower the price below the
margin of profit.
Twenty-two miles still further east we find the colony of Omaja,
boasting a population of nearly 300 people, most of whom are Americans,
although a number are from England and Canada. A small group of hard
working Finlanders, too, have joined their fortunes with the settlers of
Omaja. The surrounding country is quite attractive, and was at one time a
huge cattle ranch, covering some 50,000 acres of land, divided between
heavy forests and open savannas.
Omaja has the usual complement of post-office, school-house, churches
and stores, with a sufficient variety of creeds to satisfy almost any
community. Some 700 or 800 acres of citrus fruit have been planted in
Omaja, about one-half of which is grape-fruit and Valencia oranges. Omaja
has an encouraging amount of social and musical activity which lightens the
more serious burdens of life in the colony.
Some 30 miles north of Santiago de Cuba, and 50 miles south of Antilla,
the shipping point on Nipe Bay, are two small colonies only a few miles
apart known as Paso Estancia and Bayate. There are some 40 or 50
permanent settlers in Paso Estancia, Americans, Canadians and English.
They have made clearings in the thick virgin forests and made for
themselves comfortable and rather artistic little homes; frame buildings
covered with zinc roofs, perched on hillsides, convenient to swift running
streams.
The “Royal Palm” Hotel, a cement building, furnishes accommodations
for newcomers and guests. The view from the hotel, looking across a
delightful panorama of forest covered hills and valleys, gives a certain
lasting charm to the vicinity.
The settlers of this section evidently were advised of the mistakes made
in other parts of the Island, and while the growing of citrus fruits seems to
have been the main object, food products, corn, vegetables, coffee, cacao,
cattle, hogs and forage were not neglected.
A few miles south is the colony of Bayate, settled very largely by
Swedish Americans, whose programme has been quite a departure from that
of other colonists in Cuba. Their children are being taught Spanish in the
schools so that they may bring their parents more closely in contact with
their Spanish speaking neighbors. There are approximately 200 settlers in
this community, most of whom have devoted their energies to growing
sugar cane, for which the land in the neighborhood is excellently adapted.
The Auza mill, twelve miles further down the railroad, buys all of the cane
they can raise, giving them in exchange 5½ lbs. of sugar for every 100
pounds of cane. There is a very decent little hotel, built of mahogany and
cedar, furnishing accommodations to guests who may happen to stop.
Bayate has its school house, for which the Cuban Government furnishes
two teachers, one of whom teaches in Spanish and the other in English.
Most of the settlers have their own cows, pigs and an abundance of
chickens. Some of them are planting coffee and cacao on the hill sides. Two
crops of corn may be easily grown in this section, and nothing perhaps in
Cuba, brings a better price, especially in the western end of the Island.
It would seem quite probable that general farming will eventually take
the place of the citrus fruit grove in Cuba, as a source of permanent income
and profit. The demand for sugar, brought about by the European War,
greatly increased the acreage of cane, and has undoubtedly saved many
American colonies, especially those of Oriente, from economical disaster.
It is to be hoped that the Cuban Government, in the future, may be
induced to provide some kind of supervision over projected colonies in
regard to the selection of localities, the character of soil, and the election of
agricultural undertakings which will insure success. It is the desire of the
Government that all homeseekers, if possible, may find life in Cuba both
pleasant and profitable, and only in some such way can the mistakes of
colonization in the past be avoided.
INDEX
A, B, C, D, F, G, H, I, M, O, P, R, S, T, V, W, Y.
Agramonte, General Eugenio Sanchez, Secretary of Agriculture, 154.
Agriculture, 144;
typical rural home view, 145;
natural advantages of soil and climate, 145;
Department of Agriculture, 148;
Division of Agriculture, 148; of Commerce, 149;
of Veterinary Science and Animal Industry, 149;
of Forestry and Mines, 149;
of Trade Marks and Patents, 150;
of Meteorology, 150;
of Immigration, Colonization and Labor, 150;
of Game and Bird Protection, 151;
of Publicity and Exchanges, 152;
Experiment Station, 153;
breeding live stock, 155;
fruits and vegetables, 156;
combatting insects and diseases, 157;
“black fly,” 157.
See Grains, Grass, Fruit, Vegetables, Stock-Raising.
American Colonists, 80, 103, 390;
deluded by speculators, 391;
ill-chosen sites, 391;
La Gloria, 392;
relations with the Cubans, 392;
increasing and assured prosperity for those who persevere, 393;
Isle of Pines, 394;
Herradura, Pinar del Rio, 396;
Bartle, 398;
Victoria de las Tunas, 399;
Omaja, 399;
Paso Estancia and Bayate, 400.
American Legation at Havana, 298.
Animals, Indigenous, 257;
the hutia, 257;
sandhill crane, 258;
guinea fowl, 258;
turkey, 259;
quail, 259;
buzzard, 259;
sparrow hawk, 259;
mocking bird, 259;
pigeons, 259;
parrots, 260;
tody, 260;
orioles, 260;
lizard cuckoo, 261;
trogon, 261;
flamingo, 262;
Sevilla, 262;
ani, 262.
See Poultry, Stock Raising, Bees.
Asphalt and Petroleum:, 126;
early discovery of pitch, 126;
observations of Alexander von Humboldt, 127;
in Havana Province, 128;
in Matanzas, 128;
in Pinar del Rio, 129;
many wells sunk, 130, et seq.
Atkins, Edward F., Sugar promoter, 177.
Banking. See Money and Banking.
Bees, for honey and wax, 280;
exceptional facilities for culture, 281;
trade in wax, 282.
Birds. See Animals.
Botanic Gardens, 301.
Cacao, 233;
for food and drink, 234;
varieties, 236;
culture, 236.
Camaguey Province, 71;
history, 71;
topography, 74;
harbor of Nuevitas, 78;
resources and industries, 79;
American colonies, 80;
Camaguey City, 82;
chrome deposits, 116.
Canning, opportunity for industry, in pineapples, 226.
Cardenas, City, 56;
City Hall and Plaza, scene, 56;
Industries, 57;
mines, 58.
Cauto River, 85.
Chocolate. See Cacao.
Chrome. Sec Mines and Mining.
Cienaga de Zapata, 67; plans for draining, 165.
Cienfuegos, 65.
Clay and Cement, 27.
Climate, 19;
equable temperature, 19;
rainfall, 20;
at Havana, 31.
Cocoa. See Cacao.
Coffee, 197;
origin of Cuban plantations, 197;
many abandoned groves, 198;
methods of culture, 199;
profits of crop, 199; marketing, 200; encouragement for the industry,
201.
Commerce. See Ocean Transportation, and Railroads.
Cork Palm, 38.
Customs. See Ocean Transportation.
Drives: A Paradise of Palm-shaded automobile highways, 326;
roads radiating from Havana, 327;
to Matanzas, 328;
to Artemisa, 328;
to Candelaria, 329;
San Cristobal, 329;
Bahia Honda, 320;
San Diego de los Banos, 330;
Pinar del Rio, 331;
Valley of Vinales, 331;
Mariel, 333;
radiating from Matanzas, 335;
Cardenas, 336;
Cienfuegos, 336;
Trinidad, 336;
radiating from Santa Clara, 337;
Camaguey, 337;
Santiago, 337;
among Mountains of Oriente, 338.
Forestry, 135;
great number and variety of trees, 135;
alphabetical list of sixty leading kinds, with characteristics of each, 136,
et seq.;
location of timber lands, 142;
extent, 143.
Fruits: Aguacate, 228;
varieties, 229;
for salads, 230.
Anon, or sugar apple, 226.
Bananas, the world’s greatest fruit, 219;
methods of use, 219;
grown for commerce, 220;
soil and cultivation, 221;
varieties, 222;
possibilities of the crop, 223.
Chirimoya, 226.
Citrus fruits, 211;
orange groves, 212;
discretion and care needed in culture, 214;
varieties of oranges, 215;
grape fruit, 217;
limes, 217.
Figs, 228. Grapes, 232;
experiments with various kinds, 233;
wine-making, 233.
Guava, 228.
Mamey, 227.
Mamoncillo, 228.
Mango, foremost fruit of Cuba, 203;
the Manga, 204;
varieties and characteristics, 204, et seq.;
for both fruit and shade, 209;
fruit vender in Havana, scene, 209.
Pineapples, 224;
soil and culture, 224;
profits of crop, 225;
varieties, 225;
for canning, 226.
Sapodilla, see Zapote.
Tamarind, 227.
Zapote, 226.
Grain: Indian corn, 248;
Kaffir corn, 249;
millet, 249;
wheat, 249;
rice, 250;
opportunities for rice culture, 251.
Grasses and Forage Plants: Parana grass, 253;
Bermuda grass, 253;
alfalfa, 253; cow peas, 254;
beans, 255;
peanuts, 255.
Guantanamo, 89.
Harbors: Havana, 28, 342;
Mariel, 41, 341;
Cabanas, 42, 341;
Bahia Honda, 42, 341;
Cienfuegos, 65, 349;
Nuevitas, 78, 345;
Nipe, 87, 346;
Guantanamo, 89, 347;
Santiago, 87, 348;
Matanzas, 343;
Cardenas, 344;
Sagua, 344;
Caibarien, 344;
Manati, 345;
Puerto Padre, 346;
Banes, 346;
Cabonico and Levisa, 347;
Sagua de Tanamo, 347;
Baracoa, 347;
Manzanillo, 349;
Batabano, 350.
Minor
harbors, 350, et seq.
Hawley, Robert B., Sugar promoter, 175.
Havana, City: history, 303;
famous streets and buildings, 304 et seq.;
modern development of city and suburbs, 307;
El Vedado, 308;
places of Interest, 309;
National Theatre, 310;
the Prado, 310;
parks, 211;
Colon Cemetery, 311;
Municipal Band and other musical organizations, 312;
Conservatory of Music, 312;
drives, 313;
bathing beaches, 313, 314;
Havana Yacht Club, 314;
fishing, 314;
Jai Alai, 315;
baseball, 316;
horse racing, 317;
golf, 317;
the Templete, 317;
the Maestranza, 318;
Department of Sanitation, 318;
La Hacienda, 319;
old Governor-General’s palace, 319;
Senate Chamber, 320;
“General Wood Laboratory,” 321;
School of Industrial Arts and Sciences, 322;
Academy of Sciences and Fine Arts, 322;
President’s Palace, 322;
new Capitol, 324;
National Hospital 325.
See Places of Historical Interest.
Havana, Province: topography, 21;
Valley of the Guines, 23;
tobacco region, 24;
forests, 25;
agriculture and horticulture, 26;
industries, 27;
harbor of Havana, 28;
water supply, 30;
climate, 31.
Henequen: world-wide importance, 53;
brought from Yucatan, 190;
first plantation, 191;
International Harvester Company’s plantation, 191;
possibilities of extension of the industry, 192;
advantages of soil and climate, 193;
estimates of cost and profit, 195.
Himely, H. A., estimates Sugar crop, 166.
Holguin, 93.
Iron. See Mines and Mining.
Magotes, 14.
Manganese. See Mines and Mining.
Manzanillo, 92.
Matanzas Province: Topography, 49;
drainage system, 49;
Yumuri River and Valley, 51;
resources, 52;
henequen and sisal, 53;
Matanzas City, 54;
Caves of Bellamar, 55;
Cardenas, 56;
mines, 58;
sugar, 58;
chrome, 116.
Menocal, Mario G., Sugar promoter, 175.
Mines and Mining: Pinar del Rio, 47;
Matanzas, 58;
Oriente, 96;
early search for gold, 104.
Copper: El Cobre mines, 105;
near Havana, 106;
Bayamo, 107;
Matanzas, 108;
Santa Clara, 108;
Camaguey, 108;
Pinar del Rio, 109;
American interests in, 109;
Matahambre mines, 110.
Iron, in Oriente, 111;
Camaguey, 112;
Pinar del Rio, 112;
nickeliferous ores, 112;
statistics of shipments of iron and copper ores, 112.
Manganese, in Oriente, Pinar del Rio and Santa Clara, 115, 120, 121,
122;
analysis of ore, 123; output, 124.
Chrome, in Havana, Matanzas, Camaguey and Oriente, 115;
United States Geological Survey’s prospects, 114, 117;
many rich deposits, 117 et seq.
Money and Banking: Early monetary systems, 361;
double standard adopted, 363;
stabilization under American occupation, 363;
present standard and unit, 364;
statistics, 364;
list of principal banks of Cuba, 366.
Ocean Transportation: United Fruit Company, origin of, 376;
Lorenzo D. Baker and Andrew D. Preston, 377;
Minor C. Keith’s Costa Rica railroad, 378;
development of world’s greatest agricultural transportation company,
379;
magnitude of its fleet, 379.
New York and Cuba Mail Company, origin and development of, 380;
Ward, Alexandria and other lines merged, 381;
extent of service, 381 et seq.;
its fleet, 382.
Munson Steamship Line, 383;
extent of its service, 383.
Peninsular and Occidental Steamship Company, 383;
its great ocean and railroad ferry from Havana to Key West, 384.
Pinillos Izquiendo Line, between Cuba and Spain, 384;
its large fleet, 385.
Southern Pacific, formerly Morgan, Line, 385.
French Line, 385;
its fleet, 386.
Japanese Line, Osaka Shosen Kaisha, 386.
Customs regulations, 387;
invoices, 387;
consular fees, 389;
Cuban consulates in United States and its territories, 389.
Organ Mountains, 13.
Oriente Province: Topography, 83;
picture of mountain road, 84;
rivers, 85;
sugar, 86;
Guantanamo, 89;
Santiago, 89;
resources and industries, 95;
mines, 96;
iron, 110;
chrome and manganese, 117.
Packing Houses, opportunity for, 273.
“Paradise of Palm Drives,” 326.
People of Cuba: Their hospitality and other traits, 1;
domestic habits, 2;
racial descent, 3;
Gallegos and Catalans, 5;
English, 5;
Irish, 6;
Italians, 6;
Germans, 7;
Americans, 7.
Petroleum. See Asphalt.
Pinar Del Rio Province: Topography, 34;
Valley of Vinales, 36;
harbors, 41;
Pinar del Rio City, 45;
Vuelta Abajo tobacco region, 45;
mines, 47.
Places of Historic Interest, 284-302:
Atares Fort, 300;
Bayamo, 92;
Belen Convent and College, 298;
Bellamar Caves, 55;
Cabanas, la, 286;
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Javascript Web Applications Otx Alex Maccaw
PDF
www.webre24h.com - [O`reilly] javascript cookbook - [powers]
PDF
Continuous Enterprise Development In Java Testable Solutions With Arquillian ...
PDF
Learning React Native Building Native Mobile Apps With Javascript 2nd Edition...
PDF
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
PDF
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
PDF
Kotlin Cookbook A Problemfocused Approach 1st Edition Ken Kousen
PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Javascript Web Applications Otx Alex Maccaw
www.webre24h.com - [O`reilly] javascript cookbook - [powers]
Continuous Enterprise Development In Java Testable Solutions With Arquillian ...
Learning React Native Building Native Mobile Apps With Javascript 2nd Edition...
[FREE PDF sample] Programming Entity Framework DbContext 1st Edition Julia Le...
Javascript The Definitive Guideactivate Your Web Pages 6th Ed Flanagan
Kotlin Cookbook A Problemfocused Approach 1st Edition Ken Kousen
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor

Similar to Jquery Cookbook Solutions Examples For Jquery Developers Lindley (20)

PDF
Java Power Tools 1st Edition John Ferguson Smart
PDF
Jquery In Action Second Edition 2nd Ed Bear Bibeault Yehuda Katz
PDF
Kotlin Cookbook A Problem Focused Approach 1st Edition Ken Kousen
PDF
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
PDF
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
PDF
Sustainable Web Development With Ruby On Rails Practical Tips For Building We...
PDF
DOM Enlightenment Exploring JavaScript and the Modern DOM 1st Edition Lindley...
PDF
Php Cookbook Solutions Examples For Php Programmers 3rd David Sklar Adam Trac...
PDF
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
PDF
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
PDF
WebWork in Action In Action First Edition Patrick Lightbody
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PDF
OpenGL Spec 4.4 Core
PDF
Selenium python
PDF
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
PDF
Learning Java 4th Edition Patrick Niemeyer Daniel Leuck
PDF
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
PDF
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
PDF
High Performance JavaScript Build Faster Web Application Interfaces 1st Editi...
Java Power Tools 1st Edition John Ferguson Smart
Jquery In Action Second Edition 2nd Ed Bear Bibeault Yehuda Katz
Kotlin Cookbook A Problem Focused Approach 1st Edition Ken Kousen
iOS 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
Programming Windows Store Apps with C 1st Edition Matthew Baxter-Reynolds
Sustainable Web Development With Ruby On Rails Practical Tips For Building We...
DOM Enlightenment Exploring JavaScript and the Modern DOM 1st Edition Lindley...
Php Cookbook Solutions Examples For Php Programmers 3rd David Sklar Adam Trac...
Ios 7 Programming Cookbook 2nd Edition Vandad Nahavandipoor
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
WebWork in Action In Action First Edition Patrick Lightbody
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
OpenGL Spec 4.4 Core
Selenium python
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Learning Java 4th Edition Patrick Niemeyer Daniel Leuck
Programming Ios 4 Fundamentals Of Iphone Ipad And Ipod Touch Development 1st ...
Learning React Native Building Native Mobile Apps with JavaScript 2nd Edition...
High Performance JavaScript Build Faster Web Application Interfaces 1st Editi...
Ad

Recently uploaded (20)

PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Institutional Correction lecture only . . .
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Cell Types and Its function , kingdom of life
PDF
Complications of Minimal Access Surgery at WLH
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Basic Mud Logging Guide for educational purpose
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
master seminar digital applications in india
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
VCE English Exam - Section C Student Revision Booklet
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Institutional Correction lecture only . . .
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Cell Types and Its function , kingdom of life
Complications of Minimal Access Surgery at WLH
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Basic Mud Logging Guide for educational purpose
Supply Chain Operations Speaking Notes -ICLT Program
TR - Agricultural Crops Production NC III.pdf
Microbial disease of the cardiovascular and lymphatic systems
Pharmacology of Heart Failure /Pharmacotherapy of CHF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
master seminar digital applications in india
O7-L3 Supply Chain Operations - ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPH.pptx obstetrics and gynecology in nursing
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
Ad

Jquery Cookbook Solutions Examples For Jquery Developers Lindley

  • 1. Jquery Cookbook Solutions Examples For Jquery Developers Lindley download https://ebookbell.com/product/jquery-cookbook-solutions-examples- for-jquery-developers-lindley-22034660 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Jquery Cookbook Cody Lindley Simon St Laurent https://ebookbell.com/product/jquery-cookbook-cody-lindley-simon-st- laurent-2466982 Php Jquery Cookbook Vijay Joshi https://ebookbell.com/product/php-jquery-cookbook-vijay-joshi-2531248 Aspnet Jquery Cookbook Sonal Aneel Allana https://ebookbell.com/product/aspnet-jquery-cookbook-sonal-aneel- allana-2243906 Aspnet Jquery Cookbook 2nd Edition Over 60 Recipes For Writing Client Script In Aspnet 46 Applications Using Jquery Sonal Aneel Allana https://ebookbell.com/product/aspnet-jquery-cookbook-2nd-edition- over-60-recipes-for-writing-client-script-in-aspnet-46-applications- using-jquery-sonal-aneel-allana-5476280
  • 3. Jquery Mobile Cookbook Chetan K Jain https://ebookbell.com/product/jquery-mobile-cookbook-chetan-k- jain-2624350 Jquery Ui Cookbook Adam Boduch https://ebookbell.com/product/jquery-ui-cookbook-adam-boduch-4430518 Jquery 20 Development Cookbook 1st Edition Leon Revill https://ebookbell.com/product/jquery-20-development-cookbook-1st- edition-leon-revill-23866524 Jquery For Designers Meap Remy Sharp https://ebookbell.com/product/jquery-for-designers-meap-remy- sharp-46601000 Jquery Ui In Action 1st Edition Tj Vantoll https://ebookbell.com/product/jquery-ui-in-action-1st-edition-tj- vantoll-46635972
  • 9. jQuery Cookbook jQuery Community Experts Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo
  • 10. jQuery Cookbook by jQuery Community Experts Copyright © 2010 Cody Lindley. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Editor: Simon St.Laurent Production Editor: Sarah Schneider Copyeditor: Kim Wimpsett Proofreader: Andrea Fox Production Services: Molly Sharp Indexer: Fred Brown Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: November 2009: First Edition. O’Reilly and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. jQuery Cookbook, the image of an ermine, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. TM This book uses RepKover, a durable and flexible lay-flat binding. ISBN: 978-0-596-15977-1 [S] 1257774409
  • 11. Table of Contents Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii 1. jQuery Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Including the jQuery Library Code in an HTML Page 9 1.2 Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load 10 1.3 Selecting DOM Elements Using Selectors and the jQuery Function 13 1.4 Selecting DOM Elements Within a Specified Context 15 1.5 Filtering a Wrapper Set of DOM Elements 16 1.6 Finding Descendant Elements Within the Currently Selected Wrapper Set 18 1.7 Returning to the Prior Selection Before a Destructive Change 19 1.8 Including the Previous Selection with the Current Selection 20 1.9 Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements 21 1.10 Creating, Operating on, and Inserting DOM Elements 23 1.11 Removing DOM Elements 24 1.12 Replacing DOM Elements 26 1.13 Cloning DOM Elements 27 1.14 Getting, Setting, and Removing DOM Element Attributes 29 1.15 Getting and Setting HTML Content 30 1.16 Getting and Setting Text Content 31 1.17 Using the $ Alias Without Creating Global Conflicts 32 2. Selecting Elements with jQuery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 2.1 Selecting Child Elements Only 36 2.2 Selecting Specific Siblings 37 v
  • 12. 2.3 Selecting Elements by Index Order 39 2.4 Selecting Elements That Are Currently Animating 41 2.5 Selecting Elements Based on What They Contain 42 2.6 Selecting Elements by What They Don’t Match 43 2.7 Selecting Elements Based on Their Visibility 43 2.8 Selecting Elements Based on Attributes 44 2.9 Selecting Form Elements by Type 46 2.10 Selecting an Element with Specific Characteristics 47 2.11 Using the Context Parameter 48 2.12 Creating a Custom Filter Selector 50 3. Beyond the Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 3.1 Looping Through a Set of Selected Results 53 3.2 Reducing the Selection Set to a Specified Item 56 3.3 Convert a Selected jQuery Object into a Raw DOM Object 59 3.4 Getting the Index of an Item in a Selection 62 3.5 Making a Unique Array of Values from an Existing Array 64 3.6 Performing an Action on a Subset of the Selected Set 67 3.7 Configuring jQuery Not to Conflict with Other Libraries 69 3.8 Adding Functionality with Plugins 72 3.9 Determining the Exact Query That Was Used 74 4. jQuery Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 4.1 Detecting Features with jQuery.support 77 4.2 Iterating Over Arrays and Objects with jQuery.each 79 4.3 Filtering Arrays with jQuery.grep 80 4.4 Iterating and Modifying Array Entries with jQuery.map 81 4.5 Combining Two Arrays with jQuery.merge 81 4.6 Filtering Out Duplicate Array Entries with jQuery.unique 82 4.7 Testing Callback Functions with jQuery.isFunction 82 4.8 Removing Whitespace from Strings or Form Values with jQuery.trim 83 4.9 Attaching Objects and Data to DOM with jQuery.data 84 4.10 Extending Objects with jQuery.extend 85 5. Faster, Simpler, More Fun . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 5.1 That’s Not jQuery, It’s JavaScript! 87 5.2 What’s Wrong with $(this)? 88 5.3 Removing Redundant Repetition 91 5.4 Formatting Your jQuery Chains 92 5.5 Borrowing Code from Other Libraries 94 5.6 Writing a Custom Iterator 96 5.7 Toggling an Attribute 99 vi | Table of Contents
  • 13. 5.8 Finding the Bottlenecks 101 5.9 Caching Your jQuery Objects 105 5.10 Writing Faster Selectors 107 5.11 Loading Tables Faster 109 5.12 Coding Bare-Metal Loops 112 5.13 Reducing Name Lookups 115 5.14 Updating the DOM Faster with .innerHTML 117 5.15 Debugging? Break Those Chains 118 5.16 Is It a jQuery Bug? 120 5.17 Tracing into jQuery 121 5.18 Making Fewer Server Requests 123 5.19 Writing Unobtrusive JavaScript 126 5.20 Using jQuery for Progressive Enhancement 128 5.21 Making Your Pages Accessible 130 6. Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 6.1 Finding the Dimensions of the Window and Document 135 6.2 Finding the Dimensions of an Element 137 6.3 Finding the Offset of an Element 139 6.4 Scrolling an Element into View 141 6.5 Determining Whether an Element Is Within the Viewport 143 6.6 Centering an Element Within the Viewport 146 6.7 Absolutely Positioning an Element at Its Current Position 147 6.8 Positioning an Element Relative to Another Element 147 6.9 Switching Stylesheets Based on Browser Width 148 7. Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 7.1 Sliding and Fading Elements in and out of View 153 7.2 Making Elements Visible by Sliding Them Up 156 7.3 Creating a Horizontal Accordion 157 7.4 Simultaneously Sliding and Fading Elements 161 7.5 Applying Sequential Effects 162 7.6 Determining Whether Elements Are Currently Being Animated 164 7.7 Stopping and Resetting Animations 165 7.8 Using Custom Easing Methods for Effects 166 7.9 Disabling All Effects 168 7.10 Using jQuery UI for Advanced Effects 168 8. Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 8.1 Attaching a Handler to Many Events 172 8.2 Reusing a Handler Function with Different Data 173 8.3 Removing a Whole Set of Event Handlers 175 8.4 Triggering Specific Event Handlers 176 Table of Contents | vii
  • 14. 8.5 Passing Dynamic Data to Event Handlers 177 8.6 Accessing an Element ASAP (Before document.ready) 179 8.7 Stopping the Handler Execution Loop 182 8.8 Getting the Correct Element When Using event.target 184 8.9 Avoid Multiple hover() Animations in Parallel 185 8.10 Making Event Handlers Work for Newly Added Elements 187 9. Advanced Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 9.1 Getting jQuery to Work When Loaded Dynamically 191 9.2 Speeding Up Global Event Triggering 192 9.3 Creating Your Own Events 195 9.4 Letting Event Handlers Provide Needed Data 198 9.5 Creating Event-Driven Plugins 201 9.6 Getting Notified When jQuery Methods Are Called 205 9.7 Using Objects’ Methods as Event Listeners 208 10. HTML Form Enhancements from Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 10.1 Focusing a Text Input on Page Load 212 10.2 Disabling and Enabling Form Elements 213 10.3 Selecting Radio Buttons Automatically 216 10.4 (De)selecting All Checkboxes Using Dedicated Links 218 10.5 (De)selecting All Checkboxes Using a Single Toggle 219 10.6 Adding and Removing Select Options 221 10.7 Autotabbing Based on Character Count 222 10.8 Displaying Remaining Character Count 224 10.9 Constraining Text Input to Specific Characters 226 10.10 Submitting a Form Using Ajax 228 10.11 Validating Forms 229 11. HTML Form Enhancements with Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 11.1 Validating Forms 238 11.2 Creating Masked Input Fields 247 11.3 Autocompleting Text Fields 249 11.4 Selecting a Range of Values 250 11.5 Entering a Range-Constrained Value 253 11.6 Uploading Files in the Background 255 11.7 Limiting the Length of Text Inputs 256 11.8 Displaying Labels Above Input Fields 257 11.9 Growing an Input with Its Content 259 11.10 Choosing a Date 260 12. jQuery Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 12.1 Where Do You Find jQuery Plugins? 263 viii | Table of Contents
  • 15. 12.2 When Should You Write a jQuery Plugin? 265 12.3 Writing Your First jQuery Plugin 267 12.4 Passing Options into Your Plugin 268 12.5 Using the $ Shortcut in Your Plugin 270 12.6 Including Private Functions in Your Plugin 272 12.7 Supporting the Metadata Plugin 273 12.8 Adding a Static Function to Your Plugin 275 12.9 Unit Testing Your Plugin with QUnit 277 13. Interface Components from Scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279 13.1 Creating Custom Tool Tips 280 13.2 Navigating with a File-Tree Expander 285 13.3 Expanding an Accordion 288 13.4 Tabbing Through a Document 293 13.5 Displaying a Simple Modal Window 296 13.6 Building Drop-Down Menus 303 13.7 Cross-Fading Rotating Images 305 13.8 Sliding Panels 310 14. User Interfaces with jQuery UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 14.1 Including the Entire jQuery UI Suite 317 14.2 Including an Individual jQuery UI Plugin or Two 318 14.3 Initializing a jQuery UI Plugin with Default Options 319 14.4 Initializing a jQuery UI Plugin with Custom Options 320 14.5 Creating Your Very Own jQuery UI Plugin Defaults 321 14.6 Getting and Setting jQuery UI Plugin Options 323 14.7 Calling jQuery UI Plugin Methods 323 14.8 Handling jQuery UI Plugin Events 324 14.9 Destroying a jQuery UI Plugin 326 14.10 Creating a jQuery UI Music Player 327 15. jQuery UI Theming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 15.1 Styling jQuery UI Widgets with ThemeRoller 345 15.2 Overriding jQuery UI Layout and Theme Styles 360 15.3 Applying a Theme to Non-jQuery UI Components 370 15.4 Referencing Multiple Themes on a Single Page 379 15.5 Appendix: Additional CSS Resources 388 16. jQuery, Ajax, Data Formats: HTML, XML, JSON, JSONP . . . . . . . . . . . . . . . . . . . . . . . 391 16.1 jQuery and Ajax 391 16.2 Using Ajax on Your Whole Site 394 16.3 Using Simple Ajax with User Feedback 396 16.4 Using Ajax Shortcuts and Data Types 400 Table of Contents | ix
  • 16. 16.5 Using HTML Fragments and jQuery 403 16.6 Converting XML to DOM 404 16.7 Creating JSON 405 16.8 Parsing JSON 406 16.9 Using jQuery and JSONP 407 17. Using jQuery in Large Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 17.1 Using Client-Side Storage 411 17.2 Saving Application State for a Single Session 414 17.3 Saving Application State Between Sessions 416 17.4 Using a JavaScript Template Engine 417 17.5 Queuing Ajax Requests 420 17.6 Dealing with Ajax and the Back Button 422 17.7 Putting JavaScript at the End of a Page 423 18. Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425 18.1 Automating Unit Testing 425 18.2 Asserting Results 427 18.3 Testing Synchronous Callbacks 429 18.4 Testing Asynchronous Callbacks 429 18.5 Testing User Actions 431 18.6 Keeping Tests Atomic 432 18.7 Grouping Tests 433 18.8 Selecting Tests to Run 434 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 x | Table of Contents
  • 17. Foreword When I first started work on building jQuery, back in 2005, I had a simple goal in mind: I wanted to be able to write a web application and have it work in all the major browsers—without further tinkering and bug fixing. It was a couple of months before I had a set of utilities that were stable enough to achieve that goal for my personal use. I thought I was relatively done at this point; little did I know that my work was just beginning. Since those simple beginnings, jQuery has grown and adapted as new users use the library for their projects. This has proven to be the most challenging part of developing a JavaScript library; while it is quite easy to build a library that’ll work for yourself or a specific application, it becomes incredibly challenging to develop a library that’ll work in as many environments as possible (old browsers, legacy web pages, and strange markup abound). Surprisingly, even as jQuery has adapted to handle more use cases, most of the original API has stayed intact. One thing I find particularly interesting is to see how developers use jQuery and make it their own. As someone with a background in computer science, I find it quite sur- prising that so many designers and nonprogrammers find jQuery to be compelling. Seeing how they interact with the library has given me a better appreciation of simple API design. Additionally, seeing many advanced programmers take jQuery and develop large, complex applications with it has been quite illuminating. The best part of all of this, though, is the ability to learn from everyone who uses the library. A side benefit of using jQuery is its extensible plugin structure. When I first developed jQuery, I was sure to include some simple ways for developers to extend the API that it provided. This has blossomed into a large and varied community of plugins, encom- passing a whole ecosystem of applications, developers, and use cases. Much of jQuery’s growth has been fueled by this community—without it, the library wouldn’t be where it is today, so I’m glad that there are chapters dedicated to some of the most interesting plugins and what you can do with them. One of the best ways to expand your precon- ceived notion of what you can do with jQuery is to learn and use code from the jQuery plugin community. xi
  • 18. This is largely what makes something like a cookbook so interesting: it takes the cool things that developers have done, and have learned, in their day-to-day coding and distills it to bite-sized chunks for later consumption. Personally, I find a cookbook to be one of the best ways to challenge my preconceived notions of a language or library. I love seeing cases where an API that I thought I knew well is turned around and used in new and interesting ways. I hope this book is able to serve you well, teaching you new and interesting ways to use jQuery. —John Resig Creator, Lead Developer, jQuery xii | Foreword
  • 19. Contributors Chapter Authors Jonathan Sharp has been passionate about the Internet and web development since 1996. Over the years that have followed, he has worked for startups and for Fortune 500 corporations. Jonathan founded Out West Media, LLC, in greater Omaha, Ne- braska, and provides frontend engineering and architecture services with a focus on custom XHTML, CSS, and jQuery development. Jonathan is a jQuery core team mem- ber and an author and presenter when not coding. Jonathan is most grateful for his wife, Erin; daughter, Noel; two dogs, and two horses. Rob Burns develops interactive web applications at A Mountain Top, LLC. For the past 12 years he has been exploring website development using a wide range of tools and technologies. In his spare time, he enjoys natural-language processing and the wealth of opportunity in open source software projects. Rebecca Murphey is an independent frontend architecture consultant, crafting cus- tom frontend solutions that serve as the glue between server and browser. She also provides training in frontend development, with an emphasis on the jQuery library. She lives with her partner, two dogs, and two cats in Durham, North Carolina. Ariel Flesler is a web developer and a video game programmer. He’s been contributing to jQuery since January 2007 and joined the core team in May 2008. He is 23 years old and was born in Buenos Aires, Argentina. He’s studying at the National Technological University (Argentina) and is hoping to become a systems analyst by 2010 and a systems engineer by 2012. He started working as an ASP.NET(C#) programmer and then switched to client-side development of XHTML sites and Ajax applications. He’s cur- rently working at QB9 where he develops AS3-based casual games and MMOs. Cody Lindley is a Christian, husband, son, father, brother, outdoor enthusiast, and professional client-side engineer. Since 1997 he has been passionate about HTML, CSS, JavaScript, Flash, interaction design, interface design, and HCI. He is most well known in the jQuery community for the creation of ThickBox, a modal/dialog solution. In 2008 he officially joined the jQuery team as an evangelist. His current focus has been xiii
  • 20. on client-side optimization techniques as well as speaking and writing about jQuery. His website is http://www.codylindley.com. RemySharp is a developer, author, speaker, and blogger. Remy started his professional web development career in 1999 as the sole developer for a finance website and, as such, was exposed to all aspects of running the website during, and long after, the dotcom boom. Today he runs his own development company called Left Logic in Brighton, UK, writing and coding JavaScript, jQuery, HTML 5, CSS, PHP, Perl, and anything else he can get his hands on. Mike Hostetler is an inventor, entrepreneur, programmer, and proud father. Having worked with web technologies since the mid-1990s, Mike has had extensive experience developing web applications with PHP and JavaScript. Currently, Mike works at the helm of A Mountain Top, LLC, a web technology consulting firm in Denver, Colorado. Heavily involved in open source, Mike is a member of the jQuery core team, leads the QCubed PHP5 Framework project, and participates in the Drupal project. When not in front of a computer, Mike enjoys hiking, fly fishing, snowboarding, and spending time with his family. RalphWhitbeck is a graduate of the Rochester Institute of Technology and is currently a senior developer for BrandLogic Corporation in Rochester, New York. His respon- sibilities at BrandLogic include interface design, usability testing, and web and appli- cation development. Ralph is able to program complex web application systems in ASP.NET, C#, and SQL Server and also uses client-side technologies such as XHTML, CSS, and JavaScript/jQuery in order to implement client-approved designs. Ralph of- ficially joined the jQuery team as an evangelist in October 2009. Ralph enjoys spending time with his wife, Hope, and his three boys, Brandon, Jordan, and Ralphie. You can find out more about Ralph on his personal blog. Nathan Smith is a goofy guy who has been building websites since late last century. He enjoys hand-coding HTML, CSS, and JavaScript. He also dabbles in design and information architecture. He has written for online and paper publications such as Adobe Developer Center, Digital Web, and .NET Magazine. He has spoken at venues including Adobe MAX, BibleTech, Drupal Camp, Echo Conference, Ministry 2.0, Re- fresh Dallas, and Webmaster Jam Session. Nathan works as a UX developer at Fellow- shipTech.com. He holds a Master of Divinity degree from Asbury Theological Semi- nary. He started Godbit.com, a community resource aimed at helping churches and ministries make better use of the Web. He also created the 960 Grid System, a frame- work for sketching, designing, and coding page layouts. Brian Cherne is a software developer with more than a decade of experience blue- printing and building web-based applications, kiosks, and high-traffic e-commerce websites. He is also the author of the hoverIntent jQuery plugin. When not geeking out with code, Brian can be found ballroom dancing, practicing martial arts, or studying Russian culture and language. xiv | Contributors
  • 21. Jörn Zaefferer is a professional software developer from Cologne, Germany. He cre- ates application programming interfaces (APIs), graphical user interfaces (GUIs), soft- ware architectures, and databases, for both web and desktop applications. His work focuses on the Java platform, while his client-side scripting revolves around jQuery. He started contributing to jQuery in mid-2006 and has since cocreated and maintained QUnit, jQuery’s unit testing framework; released and maintained a half dozen very popular jQuery plugins; and contributed to jQuery books as both author and tech reviewer. He is also a lead developer for jQuery UI. James Padolsey is an enthusiastic web developer and blogger based in London, UK. He’s been crazy about jQuery since he first discovered it; he’s written tutorials teaching it, articles and blog posts discussing it, and plenty of plugins for the community. James’ plans for the future include a computer science degree from the University of Kent and a career that allows him to continually push boundaries. His website is http://james .padolsey.com. Scott González is a web application developer living in Raleigh, North Carolina, who enjoys building highly dynamic systems and flexible, scalable frameworks. He has been contributing to jQuery since 2007 and is currently the development lead for jQuery UI, jQuery’s official user interface library. Scott also writes tutorials about jQuery and jQuery UI on nemikor.com and speaks about jQuery at conferences. MichaelGearystarteddevelopingsoftwarewheneditingcodemeantpunchingapaper tape on a Teletype machine, and “standards-compliant” meant following ECMA-10 Standard for Data Interchange on Punched Tape. Today Mike is a web and Android developer with a particular interest in writing fast, clean, and simple code, and he enjoys helping other developers on the jQuery mailing lists. Mike’s recent projects include a series of 2008 election result and voter information maps for Google; and StrataLogic, a mashup of traditional classroom wall maps and atlases overlaid on Google Earth. His website is http://mg.to. Maggie Wachs, Scott Jehl, Todd Parker, and Patty Toland are Filament Group. Together, they design and develop highly functional user interfaces for consumer- and business-oriented websites, wireless devices, and installed and web-based applications, with a specific focus on delivering intuitive and usable experiences that are also broadly accessible. They are sponsor and design leads of the jQuery UI team, for whom they designed and developed ThemeRoller.com, and they actively contribute to ongoing development of the official jQuery UI library and CSS Framework. Richard D. Worth is a web UI developer. He is the release manager for jQuery UI and one of its longest-contributing developers. He is author or coauthor of the Dialog, Progressbar,Selectable,andSliderplugins.Richardalsoenjoysspeakingandconsulting on jQuery and jQuery UI around the world. Richard is raising a growing family in Northern Virginia (Washington, D.C. suburbs) with his lovely wife, Nancy. They have been blessed to date with three beautiful children: Naomi, Asher, and Isaiah. Richard’s website is http://rdworth.org/. Contributors | xv
  • 22. Tech Editors Karl Swedberg, after having taught high school English, edited copy for an advertising agency, and owned a coffee house, began his career as a web developer four years ago. He now works for Fusionary Media in Grand Rapids, Michigan, where he specializes in client-side scripting and interaction design. Karl is a member of the jQuery project team and coauthor of Learning jQuery 1.3 and jQuery Reference Guide (both published by Packt). You can find some of his tips and tutorials at http://www.learningjquery.com. Dave Methvin is the chief technology officer at PCPitstop.com and one of the founding partners of the company. He has been using jQuery since 2006, is active on the jQuery help groups, and has contributed several popular jQuery plugins including Corner and Splitter. Before joining PC Pitstop, Dave served as executive editor at both PC Tech Journal and Windows Magazine, where he wrote a column on JavaScript. He continues to write for several PC-related websites including InformationWeek. Dave holds bach- elor’s and master’s degrees in computer science from the University of Virginia. David Serduke is a frontend programmer who is recently spending much of his time server side. After programming for many years, he started using jQuery in late 2007 and shortly after joined the jQuery core team. David is currently creating websites for financial institutions and bringing the benefits of jQuery to ASP.NET enterprise ap- plications. David lives in northern California where he received a bachelor’s degree from the University of California at Berkeley in electrical engineering and an MBA from St. Mary’s College. ScottMarkisanenterpriseapplicationarchitectatMedtronic.Heworksonweb-based personalized information portals and transactional applications with an eye toward maintaining high usability in a regulated environment. His key interest areas at the moment are rich Internet applications and multitouch user interface technologies. Scott lives in Minnesota with his lovely wife, two sons, and a black lab. He blogs about technology at http://scottmark.wordpress.com and long-distance trail running at http:// runlikemonkey.com. xvi | Contributors
  • 23. Preface The jQuery library has taken the frontend development world by storm. Its dead-simple syntax makes once-complicated tasks downright trivial—enjoyable, even. Many a de- veloper has been quickly seduced by its elegance and clarity. If you’ve started using the library, you’re already adding rich, interactive experiences to your projects. Getting started is easy, but as is the case with many of the tools we use to develop websites, it can take months or even years to fully appreciate the breadth and depth of the jQuery library. The library is chock-full of features you might never have known to wish for. Once you know about them, they can dramatically change how you approach the problems you’re called upon to solve. The goal of this cookbook is to expose you, dear reader, to the patterns and practices of some of the leading frontend developers who use jQuery in their everyday projects. Over the course of 18 chapters, they’ll guide you through solutions to problems that range from straightforward to complex. Whether you’re a jQuery newcomer or a griz- zled JavaScript veteran, you’re likely to gain new insight into harnessing the full power of jQuery to create compelling, robust, high-performance user interfaces. Who This Book Is For Maybe you’re a designer who is intrigued by the interactivity that jQuery can provide. Maybe you’re a frontend developer who has worked with jQuery before and wants to see how other people accomplish common tasks. Maybe you’re a server-side developer who’s frequently called upon to write client-side code. Truth be told, this cookbook will be valuable to anyone who works with jQuery—or who hopes to work with jQuery. If you’re just starting out with the library, you may want to consider pairing this book with Learning jQuery 1.3 from Packt, or jQuery in Action from Manning. If you’re already using jQuery in your projects, this book will serve to enhance your knowledge of the library’s features, hidden gems, and idiosyncrasies. xvii
  • 24. What You’ll Learn We’ll start out by covering the basics and general best practices—including jQuery in your page, making selections, and traversing and manipulation. Even frequent jQuery users are likely to pick up a tip or two. From there, we move on to real-world use cases, walking you through tried-and-true (and tested) solutions to frequent problems involving events, effects, dimensions, forms, and user interface elements (with and without the help of jQuery UI). At the end, we’ll take a look at testing your jQuery applications and integrating jQuery into complex sites. Along the way, you’ll learn strategies for leveraging jQuery to solve problems that go far beyond the basics. We’ll explore how to make the most of jQuery’s event manage- ment system, including custom events and custom event data; how to progressively enhance forms; how to position and reposition elements on the page; how to create user interface elements such as tabs, accordions, and modals from scratch; how to craft yourcodeforreadabilityandmaintainability;howtooptimizeyourcodetoeasetesting, eliminate bottlenecks, and ensure peak performance; and more. Because this is a cookbook and not a manual, you’re of course welcome to cherry-pick the recipes you read; the individual recipes alone are worth the price of admission. As a whole, though, the book provides a rare glimpse into the problem-solving approaches of some of the best and brightest in the jQuery community. With that in mind, we encourage you to at least skim it from front to back—you never know which line of code will provide the “Aha!” moment you need to take your skills to the next level. jQuery Style and Conventions jQuery places a heavy emphasis on chaining—calling methods on element selections in sequence, confident in the knowledge that each method will give you back a selection of elements you can continue to work with. This pattern is explained in depth in Chapter 1—if you’re new to the library, you’ll want to understand this concept, because it is used heavily in subsequent chapters. jQuery’s features are organized into a handful of simple categories: core functionality, selecting, manipulating, traversing, CSS, attributes, events, effects, Ajax, and utilities. Learning these categories, and how methods fit into them, will greatly enhance your understanding of the material in this book. One of the best practices this book will cover is the concept of storing element selections in a variable, rather than making the same selection repeatedly. When a selection is stored in a variable, it is commonplace for that variable to begin with the $ character, indicating that it is a jQuery object. This can make code easier to read and maintain, butitshouldbeunderstoodthatstartingthevariablenamewiththe$ characterismerely a convention; it carries no special meaning, unlike in other languages such as PHP. xviii | Preface
  • 25. In general, the code examples in this book strive for clarity and readability over com- pactness, so the examples may be more verbose than is strictly necessary. If you see an opportunity for optimization, you should not hesitate to take it. At the same time, you’ll do well to strive for clarity and readability in your own code and use minification tools to prepare your code for production use. Other Options If you’re looking for other jQuery resources, here are some we recommend: • Learning jQuery 1.3, by Jonathan Chaffer, Karl Swedberg, and John Resig (Packt) • jQuery in Action, by Bear Bibeault, Yehuda Katz, and John Resig (Manning) • jQuery UI 1.6: The User Interface Library for jQuery, by Dan Wellman (Packt) If You Have Problems Making Examples Work Before you check anything else, ensure that you are loading the jQuery library on the page—you’d be surprised how many times this is the solution to the “It’s not working!” problem. If you are using jQuery with another JavaScript library, you may need to use jQuery.noConflict() to make it play well with others. If you’re loading scripts that require the presence of jQuery, make sure you are loading them after you’ve loaded the jQuery library. Much of the code in this book requires the document to be “ready” before JavaScript can interact with it. If you’ve included code in the head of the document, make sure your code is enclosed in $(document).ready(function() { ... }); so that it knows to wait until the document is ready for interaction. Some of the features discussed in this book are available only in jQuery 1.3 and later. If you are upgrading from an older version of jQuery, make sure you’ve upgraded any plugins you’re using as well—outdated plugins can lead to unpredictable behavior. If you’re having difficulty getting an example to work in an existing application, make sure you can get the example working on its own before trying to integrate it with your existing code. If that works, tools such as Firebug for the Firefox browser can be useful in identifying the source of the problem. If you’re including a minified version of jQuery and running into errors that point to the jQuery library itself, you may want to consider switching to the full version of jQuery while you are debugging the issue. You’ll have a much easier time locating the line that is causing you trouble, which will often lead you in the direction of a solution. If you’re still stuck, consider posting your question to the jQuery Google group. Many of this book’s authors are regular participants in the group, and more often than not, someone in the group will be able to offer useful advice. The #jquery IRC channel on Freenode is another valuable resource for troubleshooting issues. Preface | xix
  • 26. If none of this works, it’s possible we made a mistake. We worked hard to test and review all of the code in the book, but errors do creep through. Check the errata (de- scribed in the next section) and download the sample code, which will be updated to address any errata we discover. If You Like (or Don’t Like) This Book If you like—or don’t like—this book, by all means, please let people know. Amazon reviews are one popular way to share your happiness (or lack of happiness), or you can leave reviews at the site for the book: http://oreilly.com/catalog/9780596159771/ There’s also a link to errata there. Errata gives readers a way to let us know about typos, errors, and other problems with the book. That errata will be visible on the page im- mediately, and we’ll confirm it after checking it out. O’Reilly can also fix errata in future printingsofthebookandonSafari,makingforabetterreaderexperienceprettyquickly. We hope to keep this book updated for future versions of jQuery, and will also incor- porate suggestions and complaints into future editions. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates Internet addresses, such as domain names and URLs, and new items where they are defined. Constant width Indicates command lines and options that should be typed verbatim; names and keywords in programs, including method names, variable names, and class names; and HTML element tags, switches, attributes, keys, functions, types, namespaces, modules, properties, parameters, values, objects, events, event handlers, macros, the contents of files, or the output from commands. Constant width bold Indicates emphasis in program code lines. Constant width italic Indicates text that should be replaced with user-supplied values. This icon signifies a tip, suggestion, or general note. xx | Preface
  • 27. This icon indicates a warning or caution. Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Answering a question by citing this book and quoting example code does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “jQuery Cookbook, by Cody Lindley. Copy- right 2010 Cody Lindley, 978-0-596-15977-1.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected]. Safari® Books Online Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly. Withasubscription,youcanreadanypageandwatchanyvideofromourlibraryonline. Read books on your cell phone and mobile devices. Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors. Copy and paste code samples, organize your favorites, down- load chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features. O’Reilly Media has uploaded this book to the Safari Books Online service. To have full digital access to this book and others on similar topics from O’Reilly and other pub- lishers, sign up for free at http://my.safaribooksonline.com. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 Preface | xxi
  • 28. 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) To comment or ask technical questions about this book, send email to: [email protected] For more information about our books, conferences, Resource Centers, and the O’Reilly Network, see our website at: http://oreilly.com —Rebecca Murphey and Cody Lindley xxii | Preface
  • 29. CHAPTER 1 jQuery Basics Cody Lindley 1.0 Introduction Since you’ve picked up a cookbook about jQuery, the authors of this book for the most part are going to assume that you have a loose idea about what exactly jQuery is and what it does. Frankly, cookbooks in general are typically written for an audience who seeks to enhance a foundation of knowledge that has already been established. Thus, the recipe-solution-discussion format is used to quickly get you solutions to common problems. However, if you are a jQuery newbie, don’t throw this book against the wall and curse us just yet. We’ve dedicated this chapter to you. If you are in need of a review or are jumping into this cookbook with little or no working knowledge of jQuery, this first chapter alone (the other chapters assume you know the basics) will aid you in learning the jQuery essentials. Now, realistically, if you have absolutely zero knowledge of JavaScript and the DOM, you might want to take a step back and ask yourself whether approaching jQuery without a basic understanding of the JavaScript core language and its relationship with the DOM is plausible. It would be my recommendation to study up on the DOM and JavaScript core before approach- ing jQuery. I highly recommend JavaScript: The Definitive Guide by David Flanagan (O’Reilly) as a primer before reading this book. But don’t let my humble opinion stop you if you are attempting to learn jQuery before you learn about the DOM and Java- Script. Many have come to a working knowledge of these technologies by way of jQuery. And while not ideal, let’s face it, it can still be done. With that said, let’s take a look at a formal definition of jQuery and a brief description of its functionality: jQuery is an open source JavaScript library that simplifies the interactions between an HTML document, or more precisely the Document Object Model (aka the DOM), and JavaScript. In plain words, and for the old-school JavaScript hackers out there, jQuery makes Dy- namic HTML (DHTML) dead easy. Specifically, jQuery simplifies HTML document 1
  • 30. traversing and manipulation, browser event handling, DOM animations, Ajax inter- actions, and cross-browser JavaScript development. With a formal explanation of jQuery under our belts, let’s next explore why you might choose to use jQuery. Why jQuery? It might seem a bit silly to speak about the merits of jQuery within this cookbook, especially since you’re reading this cookbook and are likely already aware of the merits. So, while I might be preaching to the choir here, we’re going to take a quick look at why a developer might choose to use jQuery. My point in doing this is to foster your basic knowledge of jQuery by first explaining the “why” before we look at the “how.” In building a case for jQuery, I’m not going to compare jQuery to its competitors in order to elevate jQuery’s significance. That’s because I just don’t believe that there really is a direct competitor. Also, I believe the only library available today that meets the needs of both designer types and programmer types is jQuery. In this context, jQuery is in a class of its own. Of the notorious JavaScript libraries and frameworks in the wild, I truly believe each has its own niche and value. A broad comparison is silly, but it’s nevertheless attempted all the time. Heck, I am even guilty of it myself. However, after much thought on the topic, I truly believe that all JavaScript libraries are good at something. They all have value. What makes one more valuable than the other depends more upon who is using it and how it’s being used than what it actually does. Besides, it has been my observation that micro differences across JavaScript libraries are often trivial in consideration of the broader goals of JavaScript development. So, without further philosophical ramblings, here is a list of attributes that builds a case for why you should use jQuery: • It’s open source, and the project is licensed under an MIT and a GNU General Public License (GPL) license. It’s free, yo, in multiple ways! • It’s small (18 KB minified) and gzipped (114 KB, uncompressed). • It’s incredibly popular, which is to say it has a large community of users and a healthy amount of contributors who participate as developers and evangelists. • It normalizes the differences between web browsers so that you don’t have to. • It’s intentionally a lightweight footprint with a simple yet clever plugin architecture. • Its repository of plugins is vast and has seen steady growth since jQuery’s release. • Its API is fully documented, including inline code examples, which in the world of JavaScript libraries is a luxury. Heck, any documentation at all was a luxury for years. • It’s friendly, which is to say it provides helpful ways to avoid conflicts with other JavaScript libraries. 2 | Chapter 1: jQuery Basics
  • 31. • Its community support is actually fairly useful, including several mailing lists, IRC channels, and a freakishly insane amount of tutorials, articles, and blog posts from the jQuery community. • It’s openly developed, which means anyone can contribute bug fixes, enhance- ments, and development help. • Its development is steady and consistent, which is to say the development team is not afraid of releasing updates. • Its adoption by large organizations has and will continue to breed longevity and stability (e.g., Microsoft, Dell, Bank of America, Digg, CBS, Netflix). • It’s incorporating specifications from the W3C before the browsers do. As an ex- ample, jQuery supports a good majority of the CSS3 selectors. • It’s currently tested and optimized for development on modern browsers (Chrome 1, Chrome Nightly, IE 6, IE 7, IE 8, Opera 9.6, Safari 3.2, WebKit Nightly, Firefox 2, Firefox 3, Firefox Nightly). • It’s downright powerful in the hands of designer types as well as programmers. jQuery does not discriminate. • Its elegance, methodologies, and philosophy of changing the way JavaScript is written is becoming a standard in and of itself. Consider just how many other solutions have borrowed the selector and chaining patterns. • Its unexplainable by-product of feel-good programming is contagious and certainly unavoidable; even the critics seem to fall in love with aspects of jQuery. • Its documentation has many outlets (e.g., API browser, dashboard apps, cheat sheets) including an offline API browser (AIR application). • It’s purposely bent to facilitate unobtrusive JavaScript practices. • It has remained a JavaScript library (as opposed to a framework) at heart while at the same time providing a sister project for user interface widgets and application development (jQuery UI). • Its learning curve is approachable because it builds upon concepts that most de- velopers and designers already understand (e.g., CSS and HTML). It is my opinion that the combination of the aforementioned jQuery points, and not any single attribute on its own, sets it apart from all other solutions. The total jQuery package is simply unmatched as a JavaScript tool. The jQuery Philosophy The jQuery philosophy is “Write less, do more.” This philosophy can be further broken down into three concepts: • Finding some elements (via CSS selectors) and doing something with them (via jQuery methods) • Chaining multiple jQuery methods on a set of elements 1.0 Introduction | 3
  • 32. • Using the jQuery wrapper and implicit iteration Understanding these three concepts in detail is foundational when it comes time to write your own jQuery code or augment the recipes found in this book. Let’s examine each of these concepts in detail. Find some elements and do something with them Or more specifically stated, locate a set of elements in the DOM, and then do something with that set of elements. For example, let’s examine a scenario where you want to hide a <div> from the user, load some new text content into the hidden <div>, change an attribute of the selected <div>, and then finally make the hidden <div> visible again. This last sentence translated into jQuery code would look something like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> </head> <body> <div>old content</div> <script> //hide all divs on the page jQuery('div').hide(); //update the text contained inside of all divs jQuery('div').text('new content'); //add a class attribute with a value of updatedContent to all divs jQuery('div').addClass("updatedContent"); //show all divs on the page jQuery('div').show(); </script> </body> </html> Let’s step through these four jQuery statements: • Hide the <div> element on the page so it’s hidden from the user’s view. • Replace the text inside the hidden <div> with some new text (new content). • Update the <div> element with a new attribute (class) and value (updatedContent). • Show the <div> element on the page so it’s visible again to the viewing user. If the jQuery code at this point is mystical syntax to you, that’s OK. We’ll dive into the basics with the first recipe in this chapter. Again, what you need to take away from this code example is the jQuery concept of “find some elements and do something with 4 | Chapter 1: jQuery Basics
  • 33. them.” In our code example, we found all the <div> elements in the HTML page using the jQuery function (jQuery()), and then using jQuery methods we did something with them (e.g., hide(), text(), addClass(), show()). Chaining jQuery is constructed in a manner that will allow jQuery methods to be chained. For example, why not find an element once and then chain operations onto that element? Our former code example demonstrating the “Find some elements and do something with them” concept could be rewritten to a single JavaScript statement using chaining. This code, using chaining, can be changed from this: //hide all divs on the page jQuery('div').hide(); //update the text contained inside of the div jQuery('div').text('new content'); //add a class attribute with a value of updatedContent to all divs jQuery('div').addClass("updatedContent"); //show all divs on the page jQuery('div').show(); to this: jQuery('div').hide().text('new content').addClass("updatedContent").show(); or, with indenting and line breaks, to this: jQuery('div') .hide() .text('new content') .addClass("updatedContent") .show(); Plainly speaking, chaining simply allows you to apply an endless chain of jQuery meth- ods on the elements that are currently selected (currently wrapped with jQuery func- tionality)usingthejQueryfunction.Behindthescenes,theelementspreviouslyselected before a jQuery method was applied are always returned so that the chain can continue. As you will see in future recipes, plugins are also constructed in this manner (returning wrapped elements) so that using a plugin does not break the chain. If it’s not immediately obvious, and based on the code in question, chaining also cuts down on processing overhead by selecting a set of DOM elements only once, to then be operated on numerous times by jQuery methods by way of chaining. Avoiding un- necessary DOM traversing is a critical part of page performance enhancements. When- ever possible, reuse or cache a set of selected DOM elements. 1.0 Introduction | 5
  • 34. The jQuery wrapper set A good majority of the time, if jQuery is involved, you’re going to be getting what is known as a wrapper. In other words, you’ll be selecting DOM elements from an HTML page that will be wrapped with jQuery functionality. Personally, I often refer to this as a “wrapper set” or “wrapped set” because it’s a set of elements wrapped with jQuery functionality. Sometimes this wrapper set will contain one DOM element; other times it will contain several. There are even cases where the wrapper set will contain no elements. In these situations, the methods/properties that jQuery provides will fail silently if methods are called on an empty wrapper set, which can be handy in avoiding unneeded if statements. Now, based on the code we used to demonstrate the “Find some elements and do something with them” concept, what do you think would happen if we added multiple <div> elements to the web page? In the following updated code example, I have added three additional <div> elements to the HTML page, for a total of four <div> elements: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/ jquery/1.3.0/jquery.min.js"></script> </head> <body> <div>old content</div> <div>old content</div> <div>old content</div> <div>old content</div> <script> //hide all divs on the page jQuery('div').hide().text('new content').addClass("updatedContent").show(); </script> </body> </html> You may not have explicitly written any programmatic loops here, but guess what? jQuery is going to scan the page and place all <div> elements in the wrapper set so that the jQuery methods I am using here are performed (aka implicit iteration) on each DOM element in the set. For example, the .hide() method actually applies to each element in the set. So if you look at our code again, you will see that each method that we use will be applied to each <div> element on the page. It’s as if you had written a loop here to invoke each jQuery method on each DOM element. The updated code example will result in each <div> in the page being hidden, filled with updated text, given a new class value, and then made visible again. Wrapping your head around (pun intended) the wrapper set and its default looping system (aka implicit iteration) is critical for building advanced concepts around loop- ing. Just keep in mind that a simple loop is occurring here before you actually do any additional looping (e.g., jQuery('div').each(function(){}). Or another way to look at 6 | Chapter 1: jQuery Basics
  • 35. this is each element in the wrapper will typically be changed by the jQuery method(s) that are called. Something to keep in mind here is there are scenarios that you will learn about in the coming chapters where only the first element, and not all the elements in the wrapper set, is affected by the jQuery method (e.g., attr()). How the jQuery API Is Organized There is no question that when I first started out with jQuery, my main reason for selecting it as my JavaScript library was simply that it had been properly documented (and the gazillion plugins!). Later, I realized another factor that cemented my love affair with jQuery was the fact that the API was organized into logical categories. Just by looking at how the API was organized, I could narrow down the functionality I needed. Before you really get started with jQuery, I suggest visiting the documentation online and simply digesting how the API is organized. By understanding how the API is or- ganized, you’ll more quickly navigate the documentation to the exact information you need, which is actually a significant advantage given that there are really a lot of different ways to code a jQuery solution. It’s so robust that it’s easy to get hung up on imple- mentation because of the number of solutions for a single problem. I’ve replicated here for you how the API is organized. I suggest memorizing the API outline, or at the very least the top-level categories. • jQuery Core —The jQuery Function —jQuery Object Accessors —Data —Plugins —Interoperability • Selectors —Basics —Hierarchy —Basic Filters —Content Filters —Visibility Filters —Attribute Filters —Child Filters —Forms —Form Filters • Attributes 1.0 Introduction | 7
  • 36. —Attr —Class —HTML —Text —Value • Traversing —Filtering —Finding —Chaining • Manipulation —Changing Contents —Inserting Inside —Inserting Outside —Inserting Around —Replacing —Removing —Copying • CSS —CSS —Positioning —Height and Widths • Events —Page Load —Event Handling —Live Events —Interaction Helpers —Event Helpers • Effects —Basics —Sliding —Fading —Custom —Settings • Ajax —AJAX Requests 8 | Chapter 1: jQuery Basics
  • 37. —AJAX Events —Misc. • Utilities —Browser and Feature Detection —Array and Object Operations —Test Operations —String Operations —Urls Before we jump into a sequence of basic jQuery recipes, I would like to mention that the recipes found in this chapter build on each other. That is, there is a logical formation of knowledge as you progress from the first recipe to the last. It’s my suggestion, for your first reading of these recipes, that you read them in order from 1.1 to 1.17. 1.1 Including the jQuery Library Code in an HTML Page Problem You want to use the jQuery JavaScript library on a web page. Solution There are currently two ideal solutions for embedding the jQuery library in a web page: • Use the Google-hosted content delivery network (CDN) to include a version of jQuery (used in this chapter). • Download your own version of jQuery from jQuery.com and host it on your own server or local filesystem. Discussion Including the jQuery JavaScript library isn’t any different from including any other external JavaScript file. You simply use the HTML <script> element and provide the element a value (URL or directory path) for its src="" attribute, and the external file you are linking to will be included in the web page. For example, the following is a template that includes the jQuery library that you can use to start any jQuery project: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> </head> <body> 1.1 Including the jQuery Library Code in an HTML Page | 9
  • 38. <script type="text/JavaScript"> alert('jQuery ' + jQuery.fn.jquery); </script> </body> </html> Notice that I am using—and highly recommend using for public web pages—the Google-hosted minified version of jQuery. However, debugging JavaScript errors in minified code is not ideal. During code development, or on the production site, it ac- tually might be better to use the nonminified version from Google for the purpose of debugging potential JavaScript errors. For more information about using the Google- hosted version of jQuery, you can visit the Ajax libraries API site on the Web at http:// code.google.com/apis/ajaxlibs/. It’s of course also possible, and mostly likely old hat, to host a copy of the jQuery code yourself. In most circumstances, however, this would be silly to do because Google has been kind enough to host it for you. By using a Google-hosted version of jQuery, you benefit from a stable, reliable, high-speed, and globally available copy of jQuery. As well, you reap the benefit of decreased latency, increased parallelism, and better cach- ing.ThisofcoursecouldbeaccomplishedwithoutusingGoogle’ssolution,butitwould most likely cost you a dime or two. Now, for whatever reason, you might not want to use the Google-hosted version of jQuery. You might want a customized version of jQuery, or your usage might not require/haveaccesstoanInternetconnection.Or,yousimplymightbelievethatGoogle is “The Man” and wish not to submit to usage because you are a control freak and conspiracy fanatic. So, for those who do not need, or simply who do not want, to use a Google-hosted copy of the jQuery code, jQuery can be downloaded from jQuery.com and hosted locally on your own server or local filesystem. Based on the template I’ve provided in this recipe, you would simply replace the src attribute value with a URL or directory path to the location of the jQuery JavaScript file you’ve down- loaded. 1.2 Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load Problem Modern JavaScript applications using unobtrusive JavaScript methodologies typically executeJavaScriptcodeonlyaftertheDOMhasbeencompletelyloaded.Andthereality ofthesituationisthatanyDOMtraversingandmanipulationwillrequirethattheDOM is loaded before it can be operated on. What’s needed is a way to determine when the client, most often a web browser, has completely loaded the DOM but has possibly not yet completely loaded all assets such as images and SWF files. If we were to use the window.onload event in this situation, the entire document including all assets would 10 | Chapter 1: jQuery Basics
  • 39. need to be completely loaded before the onload event fired. That’s just too time- consuming for most web surfers. What’s needed is an event that will tell us when the DOM alone is ready to be traversed and manipulated. Solution jQuery provides the ready() method, which is a custom event handler that is typically bound to the DOM’s document object. The ready() method is passed a single param- eter, a function, that contains the JavaScript code that should be executed once the DOM is ready to be traversed and manipulated. The following is a simple example of this event opening an alert() window once the DOM is ready but before the page is completely loaded: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery(document).ready(function(){//DOM not loaded, must use ready event alert(jQuery('p').text()); }); </script> </head> <body> <p>The DOM is ready!</p> </body> </html> Discussion The ready() event handler method is jQuery’s replacement for using the JavaScript core window.onload event. It can be used as many times as you like. When using this custom event, it’s advisable that it be included in your web pages after the inclusion of stylesheet declarations and includes. Doing this will ensure that all element properties are cor- rectly defined before any jQuery code or JavaScript code will be executed by the ready() event. Additionally, the jQuery function itself provides a shortcut for using the jQuery custom ready event. Using this shortcut, the following alert() example can be rewritten like so: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery(function(){ //DOM not loaded, must use ready event 1.2 Executing jQuery/JavaScript Coded After the DOM Has Loaded but Before Complete Page Load | 11
  • 40. alert(jQuery('p').text()); }); </script> </head> <body> <p>The DOM is ready!</p> </body> </html> The use of this custom jQuery event is necessary only if JavaScript has to be embedded in the document flow at the top of the page and encapsulated in the <head> element. I simply avoid the usage of the ready() event by placing all JavaScript includes and inline code before the closing <body> element. I do this for two reasons. First, modern optimization techniques have declared that pages load faster when the JavaScript is loaded by the browser at the end of a page parse. In other words, if you put JavaScript code at the bottom of a web page, then the browser will load everything in front of it before it loads the JavaScript. This is a good thing because most browsers will typically stop processing other loading initiatives until the JavaScript engine has compiled the JavaScript contained in a web page. It’s sort of a bottleneck in a sense that you have JavaScript at the top of a web page document. I realize that for some situations it’s easier to place JavaScript in the <head> element. But honestly, I’ve never seen a situation where this is absolutely required. Any obstacle that I’ve encountered during my development by placing JavaScript at the bottom of the page has been easily overcome and well worth the optimization gains. Second, if speedy web pages are our goal, why wrap more functionality around a sit- uation that can be elevated by simply moving the code to the bottom of the page? When given the choice between more code or less code, I choose less code. Not using the ready() event results in using less code, especially since less code always runs faster than more code. With some rationale out of the way, here is an example of our alert() code that does not use the ready() event: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>The DOM is ready!</p> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> alert(jQuery('p').text());//go for it the DOM is loaded </script> </body> </html> 12 | Chapter 1: jQuery Basics
  • 41. Notice that I have placed all of my JavaScript before the closing </body> element. Any additional markup should be placed above the JavaScript in the HTML document. 1.3 Selecting DOM Elements Using Selectors and the jQuery Function Problem You need to select a single DOM element and/or a set of DOM elements in order to operate on the element(s) using jQuery methods. Solution jQuery provides two options when you need to select element(s) from the DOM. Both options require the use of the jQuery function (jQuery() or alias $()). The first option, which uses CSS selectors and custom selectors, is by far the most used and most elo- quent solution. By passing the jQuery function a string containing a selector expression, the function will traverse the DOM and locate the DOM nodes defined by the expres- sion. As an example, the following code will select all the <a> elements in the HTML document: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> //alerts there are 6 elements alert('Page contains ' + jQuery('a').length + ' <a> elements!'); </script> </body> </html> If you were to run this HTML page in a web browser, you would see that the code executes a browser alert() that informs us that the page contains six <a> elements. I passed this value to the alert() method by first selecting all the <a> elements and then using the length property to return the number of elements in the jQuery wrapper set. 1.3 Selecting DOM Elements Using Selectors and the jQuery Function | 13
  • 42. You should be aware that the first parameter of the jQuery function, as we are using it here, will also accept multiple expressions. To do this, simply separate multiple selec- tors with a comma inside the same string that is passed as the first parameter to the jQuery function. Here is an example of what that might look like: jQuery('selector1, selector2, selector3').length; Our second option for selecting DOM elements and the less common option is to pass the jQuery function an actual JavaScript reference to DOM element(s). As an example, the following code will select all the <a> elements in the HTML document. Notice that I’m passing the jQuery function an array of <a> elements collected using the getElementsByTagName DOM method. This example produces the same exact results as our previous code example: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body bgcolor="yellow"> <!-- yes the attribute is depreciated, I know, roll with it --> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <a href='#'>link</a> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> //alerts there are 6 elements alert('Page contains ' + jQuery(document.getElementsByTagName('a')).length + ' <a> Elements, And has a ' + jQuery(document.body).attr('bgcolor') + ' background'); </script> </body> </html> Discussion The heavy lifting that jQuery is known for is partially based on the selector engine, Sizzle, that selects DOM element(s) from an HTML document. While you have the option, and it’s a nice option when you need it, passing the jQuery function DOM references is not what put jQuery on everyone’s radar. It’s the vast and powerful options available with selectors that make jQuery so unique. Throughout the rest of the book, you will find powerful and robust selectors. When you see one, make sure you fully understand its function. This knowledge will serve you well with future coding endeavors using jQuery. 14 | Chapter 1: jQuery Basics
  • 43. 1.4 Selecting DOM Elements Within a Specified Context Problem You need a reference to a single DOM element or a set of DOM elements in the context of another DOM element or document in order to operate on the element(s) using jQuery methods. Solution The jQuery function when passed a CSS expression will also accept a second parameter that tells the jQuery function to which context it should search for the DOM elements based on the expression. The second parameter in this case can be a DOM reference, jQuery wrapper, or document. In the following code, there are 12 <input> elements. Notice how I use a specific context, based on the <form> element, to select only par- ticular <input> elements: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <form> <input name="" type="checkbox" /> <input name="" type="radio" /> <input name="" type="text" /> <input name="" type="button" /> </form> <form> <input name="" type="checkbox" /> <input name="" type="radio" /> <input name="" type="text" /> <input name="" type="button" /> </form> <input name="" type="checkbox" /> <input name="" type="radio" /> <input name="" type="text" /> <input name="" type="button" /> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> //searches within all form elements, using a wrapper for context, alerts "8 inputs" alert('selected ' + jQuery('input',$('form')).length + ' inputs'); //search with the first form element, using DOM reference as the context, alerts 1.4 Selecting DOM Elements Within a Specified Context | 15
  • 44. //"4 inputs" alert('selected' + jQuery('input',document.forms[0]).length + ' inputs'); //search within the body element for all input elements using an expression, //alerts "12 inputs" alert('selected' + jQuery('input','body').length + ' inputs'); </script> </body> </html> Discussion It’s also possible, as mentioned in the solution of this recipe, to select documents as the context for searching. For example, it’s possible to search within the context of an XML document that is sent back from doing an XHR request (Ajax). You can find more details about this usage in Chapter 16. 1.5 Filtering a Wrapper Set of DOM Elements Problem You have a set of selected DOM elements in a jQuery wrapper set but want to remove DOM elements from the set that do not match a new specified expression(s) in order to create a new set of elements to operate on. Solution The jQuery filter method, used on a jQuery wrapper set of DOM elements, can exclude elements that do not match a specified expression(s). In short, the filter() method allows you to filter the current set of elements. This is an important distinction from the jQuery find method, which will reduce a wrapped set of DOM elements by finding (via a new selector expression) new elements, including child elements of the current wrapped set. To understand the filter method, let’s examine the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <a href="#" class="external">link</a> <a href="#" class="external">link</a> <a href="#"></a> <a href="#" class="external">link</a> <a href="#" class="external">link</a> <a href="#"></a></li> 16 | Chapter 1: jQuery Basics
  • 45. <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <a href="#">link</a> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> //alerts 4 left in the set alert(jQuery('a').filter('.external').length + ' external links'); </script> </body> </html> The HTML page in the code example just shown contains a web page with 10 <a> elements. Those links that are external links are given a class name of external. Using the jQuery function, we select all <a> elements on the page. Then, using the filter meth- od, all those elements that do not have a class attribute value of external are removed from the original set. Once the initial set of DOM elements are altered using the filter() method, I invoke the length property, which will tell me how many elements are now in my new set after the filter has been applied. Discussion It’s also possible to send the filter() method a function that can be used to filter the wrapped set. Our previous code example, which passes the filter() method a string expression, can be changed to use a function instead: alert( jQuery('a') .filter(function(index){ return $(this).hasClass('external');}) .length + ' external links' ); Notice that I am now passing the filter() method an anonymous function. This func- tion is called with a context equal to the current element. That means when I use $(this) within the function, I am actually referring to each DOM element in the wrap- per set. Within the function, I am checking each <a> element in the wrapper set to see whether the element has a class value (hasClass()) of external. If it does, Boolean true, then keep the element in the set, and if it doesn’t (false), then remove the element from the set. Another way to look at this is if the function returns false, then the element is removed. If the function returns any other data value besides false, then the element will remain in the wrapper set. You may have noticed that I have passed the function a parameter named index that I am not using. This parameter, if needed, can be used to refer numerically to the index of the element in the jQuery wrapper set. 1.5 Filtering a Wrapper Set of DOM Elements | 17
  • 46. 1.6 Finding Descendant Elements Within the Currently Selected Wrapper Set Problem You have a set of selected DOM elements (or a single element) and want to find de- scendant (children) elements within the context of the currently selected elements. Solution Use the .find() method to create a new wrapper set of elements based on the context of the current set and their descendants. For example, say that you have a web page that contains several paragraphs. Encapsulated inside of these paragraphs are words that are emphasized (italic). If you’d like to select only <em> elements contained within <p> elements, you could do so like this: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>Ut ad videntur facilisis <em>elit</em> cum. Nibh insitam erat facit <em>saepius</em> magna. Nam ex liber iriure et imperdiet. Et mirum eros iis te habent. </p> <p>Claram claritatem eu amet dignissim magna. Dignissim quam elit facer eros illum. Et qui ex esse <em>tincidunt</em> anteposuerit. Nulla nam odio ii vulputate feugait.</p> <p>In quis <em>laoreet</em> te legunt euismod. Claritatem <em>consuetudium</em> wisi sit velit facilisi.</p> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> //alerts total italic words found inside of <p> elements alert('The three paragraphs in all contain ' + jQuery('p').find('em').length + ' italic words'); </script> </body> </html> Keep in mind that we could have also written this code by passing a contextual reference as a second parameter to the jQuery function: alert('The three paragraphs in all contain ' + jQuery('em',$('p')).length + ' italic words'); Additionally, it’s worth mentioning that the last two code examples are demonstrative in purpose. It is likely more logical, if not pragmatic, to use a CSS selector expression to select all the descendant italic elements contained within the ancestor <p> elements. 18 | Chapter 1: jQuery Basics
  • 47. alert('The three paragraphs in all contain ' + jQuery('p em').length + ' italic words'); Discussion ThejQuery.find() methodcanbeusedtocreateanewsetofelementsbasedoncontext of the current set of DOM elements and their children elements. People often confuse the use of the .filter() method and .find() method. The easiest way to remember the difference is to keep in mind that .find() will operate/select the children of the current set while .filter() will only operate on the current set of elements. In other words, if you want to change the current wrapper set by using it as a context to further select the children of the elements selected, use .find(). If you only want to filter the current wrapped set and get a new subset of the current DOM elements in the set only, use .filter(). To boil this down even more, find() returns children elements, while filter() only filters what is in the current wrapper set. 1.7 Returning to the Prior Selection Before a Destructive Change Problem A destructive jQuery method (e.g., filter() or find()) that was used on a set of ele- ments needs to be removed so that the set prior to the use of the destructive method is returned to its previous state and can then be operated as if the destructive method had never been invoked. Solution jQuery provides the end() method so that you can return to the previous set of DOM elements that were selected before using a destructive method. To understand the end() method, let’s examine the following HTML. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>text</p> <p class="middle">Middle <span>text</span></p> <p>text</p> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> alert(jQuery('p').filter('.middle').length); //alerts 1 alert(jQuery('p').filter('.middle').end().length); //alerts 3 alert(jQuery('p').filter('.middle').find('span') 1.7 Returning to the Prior Selection Before a Destructive Change | 19
  • 48. .end().end().length); //alerts 3 </script> </body> </html> The first alert() statement in the code contains a jQuery statement that will search the document for all <p> elements and then apply filter() to the selected <p> elements in the set selecting only the one(s) with a class of middle. The length property then reports how many elements are left in the set: alert(jQuery('p').filter('.middle').length); //alerts 1 The next alert() statement makes use of the end() method. Here we are doing every- thing we did in the prior statement except that we are undoing the filter() method and returning to the set of elements contained in the wrapper set before the filter() method was applied: alert(jQuery('p').filter('.middle').end().length); //alerts 3 The last alert() statement demonstrates how the end() method is used twice to remove both the filter() and find() destructive changes, returning the wrapper set to its orig- inal composition: alert(jQuery('p').filter('.middle').find('span').end().end().length); //alerts 3 Discussion If the end() method is used and there were no prior destructive operations performed, an empty set is returned. A destructive operation is any operation that changes the set of matched jQuery elements, which means any traversing or manipulation method that returns a jQuery object, including add(), andSelf(), children(), closes(), filter(), find(), map(), next(), nextAll(), not(), parent(), parents(), prev(), prevAll(), siblings(), slice(), clone(), appendTo(), prependTo(), insertBefore(), insertAfter(), and replaceAll(). 1.8 IncludingthePreviousSelectionwiththeCurrentSelection Problem You have just manipulated a set of elements in order to acquire a new set of elements. However, you want to operate on the prior set as well as the current set. Solution You can combine a prior selection of DOM elements with the current selection by using the andSelf() method. For example, in the following code, we are first selecting all <div> elements on the page. Next we manipulate this set of elements by finding all <p> elements contained within the <div> elements. Now, in order to operate on both the <div> and the <p> elements found within the <div>, we could include the <div> into 20 | Chapter 1: jQuery Basics
  • 49. the current set by using andSelf(). Had I omitted the andSelf(), the border color would have only been applied to the <p> elements: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <div> <p>Paragraph</p> <p>Paragraph</p> </div> <script type="text/JavaScript" src="http://ajax.googleapis.com/ ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery('div').find('p').andSelf().css('border','1px solid #993300'); </script> </body> </html> Discussion Keep in mind that when you use the andSelf() method, it will only add into the current set being operated on and the prior set, but not all prior sets. 1.9 Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements Problem You have selected a set of DOM elements, and based on the position of the selections within the DOM tree structure, you want to traverse the DOM to acquire a new set of elements to operate on. Solution jQuery provides a set of methods for traversing the DOM based on the context of the currently selected DOM element(s). For example, let’s examine the following HTML snippet: <div> <ul> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> <li><a href="#">link</a></li> </ul> </div> 1.9 Traversing the DOM Based on Your Current Context to Acquire a New Set of DOM Elements | 21
  • 50. Now, let’s select the second <li> element using the :eq() index custom selector: //selects the second element in the set of <li>'s by index, index starts at 0 jQuery('li:eq(1)'); We now have a context, a starting point within the HTML structure. Our starting point is the second <li> element. From here we can go anywhere—well, almost anywhere. Let’s see where we can go using a couple of the methods jQuery provides for traversing the DOM. Read the comments in the code for clarification: jQuery('li:eq(1)').next() //selects the third <li> jQuery('li:eq(1)').prev() //selects the first <li> jQuery('li:eq(1)').parent() //selects the <ul> jQuery('li:eq(1)').parent().children() //selects all <li>s jQuery('li:eq(1)').nextAll() //selects all the <li>s after the second <li> jQuery('li:eq(1)').prevAll() //selects all the <li>s before the second <li> Keep in mind that these traversing methods produce a new wrapper set, and to return to the previous wrapper set, you can use end(). Discussion The traversing methods shown thus far have demonstrated simple traverses. There are two additional concepts that are important to know about traversing. The first concept and likely most obvious is that traversing methods can be chained. Let’s examine again the following jQuery statement from earlier: jQuery('li:eq(1)').parent().children() //selects all <li>'s Notice that I have traversed from the second <li> element to the parent <ul> element and then again traversed from the parent element to selecting all the children elements of the <ul> element. The jQuery wrapper set will now contain all the <li> elements contained within the <ul>. Of course, this is a contrived example for the purpose of demonstrating traversing methods. Had we really wanted a wrapper set of just <li> elements, it would have been much simpler to select all the <li> elements from the get-go (e.g., jQuery('li')). The second concept that you need to keep in mind when dealing with the traversing methods is that many of the methods will accept an optional parameter that can be used to filter the selections. Let’s take our chained example again and look at how we could change it so that only the last <li> element was selected. Keep in mind that this is a contrived example for the purpose of demonstrating how a traversing method can be passed an expression used for selecting a very specific element: jQuery('li:eq(1)').parent().children(':last') //selects the last <li> 22 | Chapter 1: jQuery Basics
  • 51. jQuery provides additional traversing methods that were not shown here. For a com- plete list and documentation, have a look at http://docs.jquery.com/Traversing. You will find these additional traversing methods used throughout this book. 1.10 Creating, Operating on, and Inserting DOM Elements Problem You want to create new DOM elements (or a single element) that are immediately selected, operated on, and then injected into the DOM. Solution If you haven’t figured it out yet, the jQuery function is multifaceted in that this one function performs differently depending upon the makeup of the parameter(s) you send it. If you provide the function with a text string of raw HTML, it will create these elements for you on the fly. For example, the following statement will create an <a> element wrapped inside of a <p> element with a text node encapsulated inside of the <p> and <a> elements: jQuery('<p><a>jQuery</a></p>'); Now, with an element created, you can use jQuery methods to further operate on the elements you just created. It’s as if you had selected the <p> element from the get-go in an existing HTML document. For example, we could operate on the <a> by using the .find() method to select the <a> element and then set one of its attributes. In the case of the following code, we are setting the href attribute with a value of http:// www.jquery.com: jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com'); This is great, right? Well, it’s about to get better because all we have done so far is create elements on the fly and manipulate those elements in code. We have yet to actually change the currently loaded DOM, so to speak. To do this, we’ll have to use the ma- nipulation methods provided by jQuery. The following is our code in the context of an HTML document. Here we are creating elements, operating on those elements, and then inserting those elements into the DOM using the appendTo() manipulation method: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> 1.10 Creating, Operating on, and Inserting DOM Elements | 23
  • 52. jQuery('<p><a>jQuery</a></p>').find('a').attr('href','http://www.jquery.com') .end().appendTo('body'); </script> </body> </html> Notice how I am using the end() method here to undo the find() method so that when I call the appendTo() method, it appends what was originally contained in the initial wrapper set. Discussion In this recipe we’ve passed the jQuery function a string of raw HTML that is taken and used to create DOM elements on the fly. It’s also possible to simply pass the jQuery function a DOM object created by the DOM method createElement(): jQuery(document.createElement('p')).appendTo('body'); //adds an empty p element to the page Of course, this could be rather laborious depending upon the specifics of the usage when a string of HTML containing multiple elements will work just fine. It’s also worth mentioning here that we’ve only scratched the surface of the manipu- lation methods by using the appendTo() method. In addition to the appendTo() method, there are also the following manipulation methods: • append() • prepend() • prependTo() • after() • before() • insertAfter() • insertBefore() • wrap() • wrapAll() • wrapInner() 1.11 Removing DOM Elements Problem You want to remove elements from the DOM. 24 | Chapter 1: jQuery Basics
  • 53. Solution The remove() method can be used to remove a selected set of elements and their children elements from the DOM. Examine the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h3>Anchors</h3> <a href='#'>Anchor Element</a> <a href='#'>Anchor Element</a> <a href='#'>Anchor Element</a> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery('a').remove(); </script> </body> </html> When the preceding code is loaded into a browser, the anchor elements will remain in the page until the JavaScript is executed. Once the remove() method is used to remove all anchor elements from the DOM, the page will visually contain only an <h3> element. It’s also possible to pass the method an expression to filter the set of elements to be removed. For example, our code could change to remove only anchors with a specific class: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h3>Anchors</h3> <a href='#' class='remove'>Anchor Element</a> <a href='#'>Anchor Element</a> <a href='#' class="remove">Anchor Element</a> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery('a').remove('.remove'); </script> </body> </html> Discussion When using the jQuery remove() method, you need to keep two things in mind: 1.11 Removing DOM Elements | 25
  • 54. • While the elements selected are removed from the DOM using remove(), they have not been removed from the jQuery wrapper set. That means in theory you could continue operating on them and even add them back into the DOM if desired. • This method will not only remove the elements from the DOM, but it will also remove all event handlers and internally cached data that the elements removed might have contained. 1.12 Replacing DOM Elements Problem You need to replace DOM nodes currently in the DOM with new DOM nodes. Solution Using the replaceWith() method, we can select a set of DOM elements for replacement. In the following code example, we use the replaceWith() method to replace all <li> elements with a class attribute of remove with a new DOM structure: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <ul> <li class='remove'>name</li> <li>name</li> <li class='remove'>name</li> <li class='remove'>name</li> <li>name</li> <li class='remove'>name</li> <li>name</li> <li class='remove'>name</li> </ul> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> jQuery('li.remove').replaceWith('<li>removed</li>'); </script> </body> </html> The new DOM structure added to the DOM is a string parameter passed into the replaceWith() method. In our example, all the <li> elements, including children ele- ments, are replaced with the new structure, <li>removed</li>. 26 | Chapter 1: jQuery Basics
  • 55. Exploring the Variety of Random Documents with Different Content
  • 56. The National University of Havana was founded under the direction of monks of the Dominican Order on January 5, 1728, and until the installation of the Republic occupied the old convent that afterwards served as the Institute. To-day the University of Havana can boast of one of the most picturesque and delightful locations occupied by any seat of learning in the world. It crowns the northeast corner of the high plateau, overlooking the capital of the Republic from the west. Its altitude is several hundred feet above the plain below, with the Gulf of Mexico close by on the north and old Morro Castle standing at the entrance of a beautiful harbor, that stretches out along the far eastern horizon, sweeping afterwards toward the south. The city of Havana fills the center of the picture, while in the immediate foreground nestle the forests of the Botanical Gardens and the Quinto de los Molinos, or summer residence of the former Spanish Governor Generals, with their beautiful drives sweeping along the front and up to the crest of the plateau. The broad stone staircase at the entrance to the grounds is quite in keeping with the dignity of the place and the numerous buildings devoted to various departments of learning are harmonious in design and commodious in appointment. A giant laurel, with an expanse of shade that would protect a small army of men, occupied the center of an old courtyard that once belonged to the fortifications commanding the Principe Heights. To these buildings will soon be added another to be known as the National School of Languages, at a cost of $150,000. This edifice, sumptuous in its appointments, will be dedicated largely to the reciprocal study of Spanish and English. American students who wish to perfect their knowledge of Spanish will be invited from the various universities of the United States to visit Cuba, at stated periods of the year, for the purpose of studying and improving their acquaintance with this language through direct contact with the students and professors of the University. The latter, on the other hand, will be afforded an excellent opportunity to perfect their knowledge of English by mingling with visiting students from the United States, and it is believed that the result of acquaintances and friendships, formed in this way, many of which will be sustained through life, will add greatly to those bonds of friendship and mutual understanding that resulted from America’s assistance to Cuba in her War for Independence, and that for a thousand reasons should never be permitted to relapse or sink into indifference.
  • 57. The national or public library of Cuba, located in the Maestranza, one of the most substantial of those old buildings that have come down from the days of Spanish dominion, was founded during the first American intervention by General Leonard Wood, on October 18, 1901. It is open to the public every day of the week except Sunday, from 8 to 11 in the morning and from 1 to 5 in the afternoon, except Saturday, when access may be secured at any time between 8 and 12 in the morning. The library contains at the present time about twenty thousand volumes. This does not however include a great mass of pamphlets and unbound manuscripts, documents, papers, etc., which form a valuable part of the collection. These volumes are largely in Spanish, French and English, and include all of the more important branches of human knowledge. Among them may be found an excellent collection of the best encyclopedias and dictionaries of those languages. Its collection of American History is extensive; in addition to which may be mentioned a valuable collection of works on international law, given by the eminent jurist Dr. Antonio S. de Bustamante, who represented the Republic of Cuba at the Peace Conference in Paris at the conclusion of the Great War. Among other gifts to the public library may be mentioned a series of large, beautiful, artistic drawings in colors, that represent all that is known of the Aztec and Toltec life existing in the Republic of Mexico at the time of the Spanish Conquest in the early part of the 16th century. These engravings have been drawn and colored with marvelous care. They are assembled in the form of an atlas which permits close study and makes one of the most interesting and valuable contributions of this kind to be found in any part of the world. They were presented to Cuba by General Porfirio Diaz, President of the Republic of Mexico. Arrangements have been made to catalogue the volumes of the library. For this purpose experts have been secured and the space amplified, and when this work is completed, while the library will not offer the luxurious quarters of institutions of its kind in other countries, it will be useful and accessible to those who wish to avail themselves of its services.
  • 58. CHAPTER XXXV OCEAN TRANSPORTATION TRANSPORTATION is the handmaid of production. Where transportation facilities are faulty, exchange of commodities is necessarily restricted to local demands, and commerce with the outside world is practically impossible. Good harbors are among the first essentials to foreign trade, and with deep, well protected bays, Cuba has been bountifully supplied. Every sheltered indentation of her two thousand miles of coast line, from the days of Colon, has been an invitation for passing ships to enter. The wealth of the island in agriculture and mineral and forest products, has made the visits of these ocean carriers profitable; hence the phenomenal growth of Cuba’s foreign commerce. In spite of the stupid restriction of trade enforced by Spain in the early colonial days, contraband commerce assumed large proportions during the 17th century, and when England’s fleet captured Havana in 1763, the capital of Cuba enjoyed a freedom of foreign exchange never before known. Quantities of sugar, coffee, hides and hardwoods, large for those times, demanded transportation during the second quarter of the 19th century. Foreign trade, too, was greatly stimulated in Cuba by conditions resulting from the Civil War in the United States. The rapid development of the sugar industry following this war soon called for more permanent lines of ocean transportation. THE CHAMBER OF COMMERCE, HAVANA The Chamber of Commerce is one of the oldest civic organizations in Cuba, which even under the repressive and discouraging rule of Spanish Governors did much for the material progress of the Island. Under the Republic its activities and achievements have of course been immensely increased, and it is now appropriately housed in one of the finest public buildings of the capital. A certain resemblance to the famous Cooper Union building in New York has often
  • 59. been remarked, though the Havana edifice is the more ornate and attractive of the two. The interdependence of produce and transportation is well illustrated in the early history of what is now known as the United Fruit Company. In 1870, Captain Lorenzo D. Baker was in command of a small, swift coasting schooner en route from Jamaica to Boston. On the wharf at Kingston lay some 40 bunches of bananas, a few of which were ripe, others lacking 10 days or more in which to change their dull green coats into the soft creamy yellow of the matured fruit. Captain Baker was fond of bananas, and ordered that the lot be placed on board his schooner, just before sailing. Fortune favored him and strong easterly beam winds brought him into the harbor of Boston in 10 days, with all of the bunches not consumed en route in practically perfect condition. Many friends of Capt. Baker, to whom this delicious fruit was practically unknown, got a taste of the banana for the first time. Among these was Andrew W. Preston, a local fruit dealer in Boston, who was greatly impressed with the appearance of the fruit, and the success which had attended Captain Baker’s effort to get the bananas into the market without injury.
  • 60. Mr. Preston reckoned that if a schooner with a fair wind could land such delicious fruit in Boston in ten days, steamers could do the same work with absolute certainty in less time. This far sighted pioneer and promoter of trade realized that three factors were essential to building up an industry of this kind. First, there must be a market for the product, and he was confident that the people of Boston and the vicinity could soon be educated to like the banana and to purchase it if offered at a fair price. Next, a sufficient and steady supply must be provided. Third, reliable transportation in the form of steamers of convenient size and suitable equipment must be secured, in order to convey the fruit with economy and regularity to the waiting market or point of consumption. True, he at first failed to interest other fruit dealers in the project. “It had never been done and consequently was a dangerous innovation that would probably prove unprofitable.” But Mr. Preston had visualized a new industry on a large scale, and with the faith of the industrial pioneer he finally succeeded in persuading nine of his friends to put up with him each $2,000, and to form a company for the purpose of growing bananas in the West Indies, of chartering a steamer suitable for the transportation, and finding a market for the produce in Boston. The details were worked out carefully and the first cargo purchased in Jamaica and landed in New England proved a decided success. During the first two or three years the accruing dividends were invested in fruit lands in Jamaica and everything went well. Not long after, however, it was found that a West Indian cyclone could destroy a banana field and put it out of business in a very few hours. More than one field or locality in which to grow bananas on a large scale was necessary to provide against the possible failure of the crop at some other point. In the meantime another broad minded and determined pioneer in the world of progress, Minor C. Keith, a youth of 23, was trying to build a railroad some 90 miles in length from Puerto Limon to the capital, San Jose, in the highlands of Costa Rica. The greater part of this road was through dense jungle and forest almost impenetrable, with nothing in the shape of freight or passengers from which revenues could be derived until the road was completed to the capital. Mr. Keith had a concession from the Costa Rican Government, but the Government had no funds with which to aid the builder in his enterprise, and this young engineer, through force of character and moral suasion, kept his two thousand workmen in line without one
  • 61. dollar of money for over 18 months. Food he managed to scrape up from various sources, but the payday was practically forgotten. In the meantime, some banana plants were secured from a plantation in Colombia, and set out on the virgin soils along the roadway through which Mr. Keith was laying his rails. These grew marvellously, and not only supplied fruit for the Jamaica negroes engaged in the work, but soon furnished bananas for export to New Orleans, and thus was started a rival industry to that of Mr. Preston, on the shores of the Western Caribbean. It was not long before Mr. Keith, who struggled for 20 years to complete his line from the coast to the capital of Costa Rica, came into contact with Mr. Preston. These captains of industry realized the advantages of co- operation, and in a very short time organized the United Fruit Company, which is probably the greatest agricultural transportation company in the world to-day. Its various plantations include lands in Colombia, Panama, Costa Rica, Honduras, Guatemala and Jamaica. Large plantations of bananas belonging to the company were until recently on the harbors of Banes and Nipe, on the north coast of Oriente, in the Island of Cuba, but these were subjected to strong breezes from the northeast that whipped the leaves and hindered their growth. Then too, it was soon discovered that these lands were better adapted to the cultivation of sugar cane, hence bananas of the United Fruit Company disappeared from the Nipe Bay district, to be replaced by sugar plantations that to-day cover approximately 37,000 acres and in 1920 will reach 50,000 acres. Over 200,000 acres on the coast of the Caribbean are devoted to the cultivation of bananas. About 30,000 head of cattle are maintained as a source of food for the thousands of laborers, mostly Jamaicans, who are employed in the fields of the United Fruit Company, which comprise an aggregate of 1,980,000 acres; while 743 miles of standard gauge railway, together with 532 miles of narrow gauge roads, are owned and operated throughout the various plantations. In the year 1915, 46,000,000 bunches of bananas were shipped by the United Fruit Company from the shores of the Caribbean to the United States, while the sugar plantations owned by the Company on the north coast of Oriente Province, in Cuba, produced sugar in 1918 that yielded a net return of $5,000,000. In order to provide transportation for this enormous agricultural output this company to-day owns and operates one of the biggest fleets of steamships in the world. Forty-five of these ships, with tonnages varying
  • 62. from 3,000 to 8,000, especially equipped for the banana trade, and with the best of accommodations for passengers, have an aggregate tonnage of 250,000; while 49 other steamers were chartered by the company before the war, making the total tonnage employed in the carrying trade approximately half a million. Nearly all these steamers, which connect the coast of the Caribbean with New York, Boston and New Orleans, touch, both coming and going, at the City of Havana, thus giving that port the advantage of unexcelled transportation facilities, and connecting Cuba not only with the more important cities of the Gulf of Mexico, New York and New England, but also with Jamaica, Caribbean ports, and the South American Republics lying beyond the Isthmus of Panama, along the western shores of that continent. No steamship line perhaps has been more closely related to the commercial development of Cuba than has the New York & Cuba Mail Steamship Company. This line had its origin in a carrying trade between Cuba and the United States started by the firm of James E. Ward & Co. The members of the firm were Mr. James E. Ward, Mr. Henry B. Booth and Mr. Wm. T. Hughes. The Company was incorporated under the laws of the State of New York and formally organized in July, 1881, with Mr. Ward as President, Mr. Booth as Vice President and Mr. Hughes as Secretary and Treasurer. When first organized the Company had only four ships, the Newport, Saratoga, Niagara and Santiago, with a gross tonnage of 10,179. Between the date of its organization and its transfer to the Maine Corporation, or during a period of 26 years, the company acquired 19 vessels, with a total gross tonnage of 84,411. In addition to the above the company has operated under foreign flags eight other ships aggregating a tonnage of 26,624. The four original steamers mentioned above were owned in part by the builders, Messrs. John Roach & Son, and a few other individuals. The original firm however sold its ships to the Company at the time of its reorganization. Of the vessels acquired by the company, the majority were built under contract by Messrs. Roach & Son, and Wm. Cramp & Sons’ Ship and Engine Building Company. Among the ships that were purchased and not built especially for this company, were the two sister ships Seguranca and Vigilancia, built in 1890 for the Brazil Line. The steamships City of Washington and City of Alexandria were originally owned by the
  • 63. Alexandria Line, and passed into the hands of the Ward Line after its organization. The Matanzas, formerly the Spanish steamer Guido, that had left London with a valuable cargo of food, munitions and money with which to pay off Spanish troops in Cuba, was captured by the American forces during the early part of the war with Spain, in an attempt to run the blockade that had been established, and was afterwards sold by the American Government to the Ward Line. The business of this company, after its organization, began with a passenger and freight service connecting the cities of Havana, Santiago and Cienfuegos with New York. With the acquisition of the Alexandria Line, the service of the company was extended to Mexico, and a number of ports have been added to its itinerary both in Cuba and in Mexico. The line to- day maintains a service on each of the following routes: New York to Havana and return; New York to Havana, Progreso, Yucatan, and Vera Cruz, returning via Progreso and Havana to New York; New York to Tampico, Mexico, calling occasionally on return voyages at other ports when cargoes are offered; New York to Guantanamo, Santiago, Manzanillo and Cienfuegos, returning according to the demands of shipping interests; New York to Nassau, in the Bahamas, Havana, and return. The sailings average about five a week and schedules are prepared from time to time to meet the requirements of trade. Passengers on this line are carried in three distinct classes, first cabin, intermediate, and steerage, the vessels being constructed with reference to suitable accommodations for the various classes. The principal railway and other connections are as follows: At New York in general with all railroads terminating at that port, as well as all foreign and domestic water lines that move traffic via that port; at Havana with the United Railways of Havana and the Cuba Railroad; at Tampico with the Mexican Central Railway for interior points in Mexico; at Progreso with the United Railways of Yucatan for Merida, Campeche and other interior points; at Vera Cruz with the National Railways of Mexico and the Interoceanic Railroad for interior points of Mexico, as well as with the Vera Cruz and Pacific Railroad for interior points of Mexico and the Pacific Coast; at Puerto Mexico with the Tehuantepec National Railway, for points on the Isthmus of Tehuantepec and on the Pacific Coast. Connection is also made at Vera Cruz with the Compañia Mexicana de Navegacion for traffic to Tuxpam, Coatzacoalcos, Tlacotalpam and Frontera, ports on the Gulf of Mexico. At Santiago connection is made with the Cuba Eastern Railway
  • 64. and Cuba Railroad for points throughout the interior of Cuba; at Guantanamo with the Cuba Eastern Railway and at Cienfuegos with the Cuban Central Railroad. The company has contracts with the United States Government for the transportation of mails between New York and Havana, and between New York, Havana and Mexico. It also has a contract with the Bahamas Government for the transportation of mails. The following is a list of the vessels owned or operated by the company. Steamers: Havana Matanzas Saratoga Antilla Mexico Camaguey Morro Castle Santiago Esperanza Bayamo Monterey Manzanillo Segurancia Yumuri Vigilancia Guantanamo Seneca Tugs and Steam Lighters: Colonia Auxiliar Nautilus Comport Neptuno Edwin Brandon Hercules The total gross tonnage of the steamers and tugs above mentioned is 84,000 tons. One of the oldest and most important lines in the carrying trade of the Caribbean is known as the Munson Steamship Line, and was founded in 1872 by Walter D. Munson. The trade began with sailing vessels but the increase in traffic was so great that these were soon replaced with steamers. The steamships in the service of the Munson Line to-day number 140, with an average tonnage of 2,500 tons each, dead weight. These vessels sail from nearly every port in Cuba, connecting the Island with nearly all of the Atlantic and Gulf Coast ports of the United States. The
  • 65. passenger steamers of the Munson Line ply between New York, Nuevitas and Nipe Bay of the Province of Oriente. The passenger steamers, although not touching at Havana, are equipped for the accommodation of passengers that leave from the ports of the eastern provinces of the Island. During the late European War twelve of the Munson steamships were placed in the service of the United States and three under the British flag. The Peninsular and Occidental Steamship Company operates a daily passenger, mail and freight service between Havana and Key West, Florida. Since 1912 this company has maintained practically a daily service between the two ports and maintains also a bi-weekly service between Havana and Port Tampa, Florida. Owing to the frequency of the sailings, the P. & O. SS. Co. is considered the official mail route between the United States and Cuba. The company operates also the Florida East Coast Car-Ferry freight service between Havana and Key West. This service was made possible by the extension of the Florida East Coast Railroad from the southern points of the peninsula out over the long line of keys that terminates in the Island of Key West. The erection of this viaduct, built at an enormous expense, of stone and concrete, was the realization of Henry W. Flagler’s dream of modern transportation facilities between the United States and Cuba. The car ferry service was inaugurated in January, 1915. At the present time two of these great car ferryboats, with a capacity of 28 standard freight cars each, make a round trip every twenty-four hours between the two ports. These two vessels transport approximately 1,150 cars in and out of Cuba every month, carrying over 35,000 tons each way in that length of time. Since the inauguration of the service more business has been offered than can be handled during certain months of the year, and it has been found necessary to refuse large quantities of cargo destined for the Republic of Cuba. The advantage of this service to the Cuban fruit and vegetable growers has been very great, since they are enabled to load in the Cuban fields freight cars belonging to almost every line in the United States, so that this produce may be shipped direct, without breaking bulk, to any market in the United States. In the year 1870 the Pinillos Izquierdo Line of steamers was established between Spain and the Island of Cuba. The home office of this line is in
  • 66. Cadiz, Spain. Their vessels are engaged in freight and passenger service touching at the following points in the Peninsula: Barcelona, Palma de Majorca, Valencia, Alicante, Malaga, Cadiz, Vigo, Gijon and Santander. En route the Canary Island and Porto Rico are also visited while the terminal points on this side of the Atlantic are New Orleans, Galveston, Havana and Santiago de Cuba. All of their steamers carry mail. Their fleet consists of nine steamers with a combined tonnage of 78,000 tons as follows: Infanta Isabel 16,500 tons2000 passengers Cadiz 10,500 tons1500 passengers Barcelona 10,500 tons1500 passengers Valbanera 10,500 tons1500 passengers Catalina 8,000 tons1000 passengers Martin Sáena 5,500 tons 800 passengers Balmes 6,500 tons 800 passengers Conde Wifredo 5,500 tons 800 passengers Miguel M. Pinillos 4,500 tons 500 passengers 78,000 tons The Southern Pacific, originally known as the Morgan line, established a transportation service between Gulf ports and the Island of Cuba many years ago, beginning with two side-wheel walking-beam steamboats of about 800 tons dead weight. They were heavy consumers of coal and had a speed of from 9½ to 11 knots. A few years later the steamers Hutchinson and Arkansas, both side wheelers, were added to the fleet. Still later the single propeller steamers Excelsior and Chalmette, of about 2,400 tons each, were placed in the service of the Southern Pacific Line. These combined freight and passenger boats were well built and seaworthy fourteen knot steamers, of an equipment considered modern at that time. The Louisiana entered the service in 1900, but owing to an error in loading freight, it turned turtle at the docks in New Orleans and became a total loss. The Excelsior and Chalmette are still maintaining an efficient weekly service between New Orleans and Havana. The Compagnie General Transatlantique, generally known as the French Line, connecting western France, Northern Spain and the Canary Islands, with Cuba, Porto Rico, Vera Cruz, Mexico, and the city of New Orleans, was established in 1860.
  • 67. St. Nazaire on the Bay of Biscay in France is the headquarters of this line. Their steamers touch at Santander and Coruña on the north coast of Spain; at the Canary Islands, Porto Rico, Martinique, Santiago de Cuba, Havana, Vera Cruz, and New Orleans. Their fleet consists of 13 ships with a combined tonnage of 153,500 tons. The steamship Lafayette, of 15,000 tons, is equipped for the accommodation of 1,620 passengers. The Espana, of 15,000 tons, carries 1,500 passengers; the Flanders, of 12,000 tons, carries 1,250 passengers; the Venizia, of 12,000 tons, carries 700 passengers; the Navarre, of 10,000 tons, carries 1,000 passengers; the Venezuela, of 7,000 tons, carries 500 passengers. The Caroline, the Mississippi and the Georgie are each steamers of 13,000 tons. The Honduras is a 12,000 ton ship; the Hudson 11,000 tons; the Californie 10,500 tons, and the Virginie 10,000 tons. The seven last mentioned vessels carry cargo only. During August, 1919, the 7,000 ton steamer Panama Canal arrived in Cuba from Japan, inaugurating a new steamship line between Japan and the United States, touching at Cuban ports. The line is known as the Osaka Shosen Kaisha, of Osaka, Japan. The fleet consists of 186 steamers plying between Japan and different parts of the world. The headquarters for this company has been established at Chicago, Illinois, owing to connections that have been made with the Chicago, Milwaukee and St. Paul Railroad. Steamers eastward bound from Japan will bring rice and general cargo, most of which will be consigned to the Island of Cuba, owing to the heavy consumption of that article of food in that Republic. New Orleans will be the terminus in the United States of the line. On the initial trip of the Panama Canal 50,000 sacks of rice grown in Japan were consigned to Cuban merchants in Santiago de Cuba and Cienfuegos. The return cargoes will be composed largely of cotton, taken aboard at New Orleans, and with sugar and tobacco shipped from Cuba to the Orient. This line has begun with one sailing each way per month, all steamers touching at Havana for freight and passengers. The Customs regulations of Cuba require five sets of invoices for Havana and four for all other points; which must be written in ink, in either English or Spanish. If they are typewritten the original imprint must be included, but the others may be carbon copies. Invoices must give the
  • 68. names of shippers and consignees, and of vessels; marks and numbers, description of merchandise, gross and net weights by metric system, price, value, and statement of expenses incurred. If there are no expenses, that fact must be stated. Prices must be detailed, on each article, and not in bulk. Descriptions of merchandise must be detailed, telling the materials of each article and of all its parts. Descriptions of fabrics must tell the nature of the fibre, character of weave, dye, number of threads in six square millimeters, length and width of piece, weight, price, and value. All measurements must be in metric units. At the foot of each sheet of the invoice must be a signed declaration, in Spanish, telling whether the articles are or are not products of the soil or industry of the United States. If the manufacturer or shipper is not a resident of the place where the consulate is situated, he must appoint in writing a local agent to present the invoice and the agent must write and sign a declaration concerning his appointment. Stated forms are prescribed and are furnished by consuls for manufacturers, producers, owners, sellers and shippers. Freight charges to the shipping port, custom house and statistical fees, stamps, wharfage and incidental expenses must be included in the dutiable value of goods, and must be stated separately; but insurance and consular fees must not be included. Each invoice must cover a single, distinct shipment, by one vessel to one consignee. Separate consignments must not be included in one invoice. Invoices under $5, covering products of the soil or industry of the United States must be certified in order to enjoy the provisions of the reciprocity treaty between the two countries. Invoices and declarations must be written on only one side of the paper, and no erasures, corrections, alterations or additions must be made, unless stated in a signed declaration. Domestic and foreign merchandise from the United States must be separately invoiced. Invoices are not required on shipments of foreign goods of less value than $5. Fabrics of mixed fibres must be so stated, with a statement of the proportion of the principal material, upon which the duty is to be computed. Cotton goods pay duty according to threads, and silk and wool ad valorem. Samples of cotton goods are taken at the custom house, and should be provided for that purpose to avoid mutilation of the piece. Duties on ready
  • 69. made clothing are based on the chief outside fabric. A surtax of 100% is placed on ready-made cotton clothing, and a surtax of 30% on colored threads. Two copies of each set of bills of lading must be given, but on merchandise of less than $5 value need not be certified. Invoices covering shipments of automobile vehicles must state maker, name of car, style of car, year of make, maker’s number on motor, number of cylinders, horse power, and passenger capacity. If after an invoice has been certified it or any part of it is delayed in shipment, the steamship company must mark on the bill of lading opposite the delayed goods “Short Shipped,” but the invoice need not be recertified. The consignee should, however, be informed. The list of articles admitted into Cuba free of duty comprises samples of fabrics, felt, and wall paper, of a prescribed size, samples of lace and trimmings, and samples of hosiery, provided that they are rendered unfit for any other purpose than that of samples; trained animals, animals, portable theatres, and other articles for public entertainment, not to remain in Cuba longer than three months; receptacles in which fruits or liquids were exported from Cuba and which are being returned empty; furniture, clothing and other personal property of immigrants, or of travellers, showing evidence of having already been used; agricultural implements not including machinery; and pictures, posters, catalogues, calendars, etc., not for sale but for free distribution for advertising purposes. The importation into Cuba is forbidden or restricted of foreign coins of anything but gold, save those of the United States; gunpowder, dynamite and other explosives, save by special permit of the Interior Department; and silencers for firearms. Arms of more than .32 caliber, .44 caliber revolvers, and automatic pistols require special permit. Consular fees for certification are: On shipments worth less than $5, nothing; from $5 upward and less than $50, fifty cents; from $50 upward and less than $200, $2; over $200, $2 plus ten cents for each $100 or fraction thereof. Extra copies of invoices, 50 cents each. Invoice blanks, ten cents a set. Certifying bills of lading, $1. Cuban consulates are situated in the United States and its possessions as follows: Atlanta, Ga.; Baltimore, Md.; Boston, Mass.; Brunswick, Ga.; Chattanooga, Tenn.; Chicago, Ill.; Cincinnati, Ohio.; Detroit, Mich.;
  • 70. Fernandina, Fla.; Galveston, Tex.; Gulfport, Miss.; Jacksonville, Fla.; Kansas City, Mo.; Key West, Fla.; Los Angeles, Cal.; Louisville, Ky.; Mobile, Ala.; New Orleans, La.; New York; Newport News, Va.; Norfolk, Va.; Pascagoula, Miss.; Pensacola, Fla.; Philadelphia, Penn.; San Francisco, Cal.; Savannah, Ga.; St. Louis, Mo.; Tampa, Fla.; Washington, D. C.; and Aguadilla, Arecibo, Mayagues, Ponce, and San Juan, Porto Rico.
  • 71. CHAPTER XXXVI AMERICAN COLONIES IN CUBA AMERICAN soldiers returning to the United States at the conclusion of her little war with Spain, in the summer of 1898, brought wonderful stories of Cuba, with glowing accounts of her climate, her rainfall, her rich soil and natural advantages. Schemes for the colonization of the Island were immediately formed and some of them put into effect during the early days of the Government of Intervention. Unfortunately, most of these enterprises originated with speculators, and so-called land-sharks, who sought only to secure large tracts of territory, at the smallest possible cost, and with the assistance of attractive literature place them on the market in the United States, at prices which would enable them, even when sold on the installment plan to make a thousand percent or more profit on the capital invested. This method of settling up the country would not have been so objectionable had the promoters of the schemes taken the pains to locate their colonies in those sections of the Island where transportation facilities, if not immediately available, could at least be reasonably sure in the near future. Up to the present, a logical, common sense plan in the colonization in this Island has in no instance been carried out. On the contrary, every American colony that has yet been established in Cuba, and her adjacent Islands, has been located with disregard to the first essentials of success. These hapless experiments have met with a fate that was inevitable and in most instances can be described with one word “Failure.” The first American Colony in Cuba was started on Broadway, New York City, by a land speculator, who, through correspondence, learned of a large property that could be had in Cuba with a small cash payment, at what seemed to be a ridiculously low price; in other words at about 80 cents an acre. An option was secured on several thousand acres, the larger part of which, perhaps, was available for general agricultural purposes. But the
  • 72. location with reference to transportation facilities was one of the most unfortunate that could have been selected. This colony was called La Gloria, and while La Gloria has not been a failure, nothing in the world has saved it but the pluck, and persistent and intelligent effort of a courageous and most commendable community of Americans. Some 800 of these, not knowing where they were going, other than that it was somewhere in Cuba, were dumped by a chartered steamer in the harbor of Nuevitas, 40 miles from their destination. This they afterwards reached with the aid of light draft schooners, or shallow, flat-bottom boats, pushed through a muddy ditch some three or four miles, and as many more over sand shoals, where the passengers were compelled to get out and wade. Worse than all, when finally landed on the south shore of Guajaba Bay, they were obliged to wade through a swamp for another five miles, in mud knee-deep, or more, in order to reach the high ground on which they were to make their future homes in a foreign land. Many of these colonists, disappointed and deceived, failed to stand the strain, and those who had the necessary funds, or could borrow, returned disgusted to their homes in the United States. Others, after studying the soil and noting the splendid growth of forest and vegetation, lulled into resignation by soft, cool breezes from the Atlantic Ocean, and the bright sunshine that seldom missed a day, made up their minds to stick to the game and to see it out, which they did. Their efforts in the end were crowned with a certain degree of success, and the near future holds out to them the promise of fairly satisfactory transportation for their fruit, vegetables and other products, to profitable markets, both in Cuba and the United States. The colony of La Gloria in the fall of 1918 contained about 75 families and comprised, all told, probably 500 people. This estimate includes the little nearby settlements of Guanaja, Punta Pelota, Columbia, Canasi, The Garden, and other little suburbs or groups of families, scattered throughout the district. With the Cubans, the people of La Gloria have always maintained the most friendly relations, while mutual esteem and respect is the rule of the district. The Mayor of La Gloria, a Cuban, was elected by popular vote, and is highly esteemed in the community as a man who has been always an enthusiastic and efficient supporter of the interests of the colony. Seventy
  • 73. per cent of the population is American. La Gloria has always been fortunate in having a good school in which both Spanish and English are taught. The town itself is located on the northern edge of the plateau, or rise of ground overlooking the savanna that separates it from the bay. A fairly good road some five miles in length, built at Government expense, connects the town with the wharf, whence, up to the winter of 1918, all produce was sent for shipment to the harbor of Nuevitas some forty miles east by launch. The streets are very wide, shaded with beautiful flowering flamboyans, and the houses, many of them two stories in height, are built of native woods, cedar, mahogany, etc., products of the saw mills of the neighborhood. These, as a rule, are kept painted, and the general appearance of the town, although not bustling with business, is one of comfort, cleanliness and thrift. It is not an exaggeration to state that there is no little town in conservative New England where less of waste, or disfiguring material, even in back yards, or rear of houses, can be found, than in the little town of La Gloria. The furnishing of most of the houses consists of a strange mingling of articles of comfort brought from home, combined with other things that have been improvised and dug out of their tropical surroundings. A mistake, made in the early days of La Gloria, and one common to every American colony in the West Indies, has been the exclusive dedication of energy, effort and capital to the growth of citrus fruit. The first essential factor to the success of a colony in any climate is food, and forage for animals. This, in nearly every American town in Cuba, has been ignored, every effort being expended on the planting and promotion of a citrus grove from which no yield could be expected inside of five or six years, and during which time, many a well meaning farmer has become discouraged or has exhausted his capital, leaving his grove in the end to be choked up with weeds and ruined by the various enemies of the citrus family. However, the people of La Gloria planted and stuck to their orange trees and many of these, today, are yielding very satisfactory returns, in spite of the serious lack of transportation. The best land belonging to the colony is located in the district known as Canasi, some three miles south of the town, in the direction of the Cubitas Mountains. There are 600 acres in this section devoted to oranges and grape
  • 74. fruit, all of which have been well cared for and are increasing in value each year. The citizens of the colony have joined forces and built a well equipped packing plant, 100 feet in length by 30 feet in width, from which, last year, were shipped 432,000 loose oranges, and 9,200 boxes of grape fruit, the latter going to the United States by the way of Nuevitas. All of this fruit at the present time is hauled by wagon, some eight or nine miles to the wharf, on the bay, whence it is conveyed to the harbor of Nuevitas for sale and shipment. La Gloria’s hope of really satisfactory transportation facilities is vested in the North Shore Railroad of Cuba, and her dream of suitable connections with the outside world of trade will soon be realized. La Gloria has many things to commend it, aside from soil and climate. One of these is excellent drinking water, found at an average depth of twenty feet. The soil on which the town is built is largely impregnated with iron ore, which forms a splendid roadbed, and enables the population to escape the seas of mud that are rather common throughout the interior, excepting along macadamized roads. Most vegetables, with the exception of potatoes, may be grown throughout the entire year in La Gloria, and a variety of potato adapted to that peculiar soil will probably be found in the near future. A serious mistake common not only in La Gloria but in nearly all other colonies in Cuba has been neglect in sowing forage plants and thus providing for live stock, so essential to the success of any farming district. That which is most to be admired in La Gloria, is the class of people who form the backbone of the colony, and who certainly came from excellent stock, proved by their successful efforts in overcoming difficulties that would have discouraged a less persevering community. The colony supports a weekly newspaper, and holds annual agricultural fairs that are a credit to the district. The second and most serious experiment in colonization in Cuba was staged in the Isle of Pines. In the year 1900 this intrepid storm sentinel of the Caribbean offered several advantages for a successful exploitation of the American public. In spite of the fact that this Island had always formed an integral part of Cuba, it was advertised throughout the United States as
  • 75. American property, and the flag raised by the Government of Intervention was pointed to as a permanent asset of that particular section. Again the promoters of this pretentious colonization scheme absolutely ignored the basic principles of success in colony work. In other words they did not take into account that not only was the Isle of Pines devoid of a first-class harbor, but that the chances of securing direct transportation between that section and the United States was decidedly remote. Through the hypnotic influence of beautifully worded advertisements and attractive pictures, large numbers of settlers from the United States and Canada, especially from Minnesota and the Dakotas, were tempted to locate in the Isle of Pines, or to purchase property, usually on the installment plan, which they had never seen, and for which they paid exorbitant prices. Tracts that cost from 90¢ to $1.20 per acre, were divided into 10, 20 and 40 acre farms, and sold at prices ranging from $25 in the beginning up to $75 and even $100 per acre in 1918. These prices have always been out of proportion to the quality of the soil, and the location of the land, since lands far more fertile, and within easy reach of steamers leaving Havana daily, might have been found on the mainland of Cuba, that would give the prospect of a fair chance of success in almost any agricultural undertaking. Here again the prospective settler was advised to start citrus fruit groves, to the exclusion of forage and other crops from which immediate returns would have encouraged the farmer, and permitted him to live economically while making up his mind as to the advisability of citrus fruit culture, which is a specialized form of horticulture, requiring much technical knowledge, and a great deal of experience to insure satisfactory results. In the Isle of Pines, as in La Gloria, while many men have been disappointed, and many families have left the country in despair, there still remains a nucleus of hard working, intelligent and enterprising men who, in spite of the disadvantages that will surround them, have made for themselves comfortable homes, and who enjoy the quiet, dreamy life that soon becomes essential to the man who remains long in the tropics. The Isle of Pines ships a considerable amount of fruit and vegetables each year, through Havana, to markets in the United States. How often the balance may be found on the profit side of the ledger, however, is open to question. The Isle of Pines undoubtedly offers an excellent retreat for those who have become tired of the strenuous life of cities, and who prefer to pass
  • 76. the remainder of their days in pleasant, healthful surroundings. To do this, of course, requires an income that will insure them against any little petty annoyance that might come from a disturbing cyclone, or a low price for grape fruit in northern markets. The enterprising promoters connected with the early colonization of the Isle of Pines made a second experiment at Herradura, in the Province of Pinar del Rio, 90 miles from the city of Havana by rail. Here they purchased some 22,000 acres of land in 1902, paying, it is said, an average price of a dollar an acre, and started the third American colony in Cuba under the name of Herradura. In the colonization work, the old La Gloria and Isle of Pines method of advertising was faithfully followed, and with results eminently satisfactory to the promoters, most of whom have acquired comfortable fortunes, at the expense of Americans and Canadians in the United States who were anxious to find homes where they could enjoy life and perhaps prosper in the Tropics. The larger part of the Herradura tract, especially that which lay along the Western Railroad, was a light sandy soil, used by the natives in the olden days for grazing cattle, and burned over every winter, thus destroying nearly all of the humus in the land. This property was divided into 40-acre tracts and sold at $20 per acre. As soon as the settlers from the United States began to arrive in any numbers, the price was advanced to $40. Citrus fruit was held out to prospective home seekers as the surest means of securing an easy life and a fortune after the first four or five years. Under favorable conditions, where all the essential elements to success are combined, this is possible. But Herradura did not combine all of the required features, hence hundreds of acres of abandoned groves can be seen along the railroad track for miles, as one enters the Herradura district. The cyclone of 1917 which added the last straw to the proverbial camel’s back, in the Isle of Pines, swept across the western end of Pinar del Rio Province also, and only those groves that had been provided with wind-breaks escaped from blight and ruin in the hurricane. Today there are about 25 families, with perhaps 100 inhabitants, remaining in the colony of Herradura. Some of these settlers, men of experience, who came from the citrus grove districts of Florida, and others who took up general farming on the better lands, some two or three miles
  • 77. north of the railroad, have succeeded, and have built for themselves comfortable homes where rural life is enjoyed to the utmost. Some of them have their machines with which they can motor over a splendid automobile drive to Havana, and spend a few days in the capital, during the opera season. Nearly all of them have a few saddle horses that furnish splendid exercise and amusement for the younger members of the colony. One of the successful old timers of Herradura is Mr. Earle, formerly chief of the Government Experimental Station at Santiago de Las Vegas, a scientific farmer and a good business man. Mr. Earle located on good land in a little valley well back from the road, planted 40 acres in citrus fruit and has succeeded where others failed. On all lands where irrigation is possible, the growing of vegetables, especially peppers and egg plants, has proven very satisfactory. The average number of crates per acre is 350, and a dollar per crate net is the estimated average profit. The irrigation comes either from wells or little streams. The raising of pigs and poultry has helped greatly all those farmers of Herradura who had the foresight not to neglect the live stock and poultry end in their farming enterprises. The price of fairly good land in Herradura today is from $25 to $50 per acre. The successful owner of a well cared for citrus grove in this colony values it at $1,500 per acre. The freight on fruit and vegetables from Herradura to the city of Havana over the Western Road, is ten cents per box. The colony boasts of a very comfortable school house, which also serves as a church and town hall. The old standbys, as they call themselves, seldom complain of their lot, and could hardly be induced to change or seek homes in other localities. There are some half dozen American and Canadian colonies in the Province of Oriente, most of them scattered along the line of the Cuba Company’s railroad that has brought the interior of that province into contact with the seaports of Antilla, on the north coast, and Santiago de Cuba on the south. The colony of Bartle is the westernmost, located about fifty miles from the borderline between that province and Oriente. The Bartle tract consisted originally of 5,000 acres, 3,000 of which lie north of the railroad and the remainder extending toward the south. Most of the land is covered with a heavy forest of hard woods and the work of clearing is a serious proposition, although the soil, once freed from stumps,
  • 78. is exceptionally rich and productive. Less than 2,000 acres have been cleared up to the present, and some three or four hundred have been planted in citrus fruit. Good water is found at a depth of 25 feet. There are approximately 200 permanent residents in this little settlement, which has been laid out to advantage with its Plantation House, hotel, church, stores, etc., and a very neat railway station. The buildings are nearly all frame, painted white with green trimmings. In Bartle, as in all colonial settlements in Cuba up to the present, the planting of citrus fruit seems to have been the aim and ambition of the settlers, who are about evenly divided between Canadians and Americans. Just south of Bartle are a number of small estates on land that belonged to the late Sir Wm. Van Horne, father of the Cuba Company Railroad. Twenty miles further east a colony has been established at Victoria de las Tunas, one of the storm centers of the various revolutionary movements on the part of the Cubans against Spanish control. There are some 800 or 900 acres of citrus fruit groves, in various stages of production, within a radius of fifteen miles surrounding the town of Victoria de las Tunas. In nearly all of the American and Canadian colonies in the Province of Oriente, settlers have learned, at times through bitter experience, that it was an economical mistake to devote all of their energies to the production of citrus groves that could give them no returns inside of five years, and that, with the exception of the local markets of Camaguey, Manzanillo and Santiago de Cuba, neither oranges nor lemons would bring a sufficient price to pay for the cost of packing, transportation and sale. Grape fruit usually yielded a profit, if the market happened to be just right; or in other words, if competing shipments from Florida and California did not lower the price below the margin of profit. Twenty-two miles still further east we find the colony of Omaja, boasting a population of nearly 300 people, most of whom are Americans, although a number are from England and Canada. A small group of hard working Finlanders, too, have joined their fortunes with the settlers of Omaja. The surrounding country is quite attractive, and was at one time a huge cattle ranch, covering some 50,000 acres of land, divided between heavy forests and open savannas. Omaja has the usual complement of post-office, school-house, churches and stores, with a sufficient variety of creeds to satisfy almost any
  • 79. community. Some 700 or 800 acres of citrus fruit have been planted in Omaja, about one-half of which is grape-fruit and Valencia oranges. Omaja has an encouraging amount of social and musical activity which lightens the more serious burdens of life in the colony. Some 30 miles north of Santiago de Cuba, and 50 miles south of Antilla, the shipping point on Nipe Bay, are two small colonies only a few miles apart known as Paso Estancia and Bayate. There are some 40 or 50 permanent settlers in Paso Estancia, Americans, Canadians and English. They have made clearings in the thick virgin forests and made for themselves comfortable and rather artistic little homes; frame buildings covered with zinc roofs, perched on hillsides, convenient to swift running streams. The “Royal Palm” Hotel, a cement building, furnishes accommodations for newcomers and guests. The view from the hotel, looking across a delightful panorama of forest covered hills and valleys, gives a certain lasting charm to the vicinity. The settlers of this section evidently were advised of the mistakes made in other parts of the Island, and while the growing of citrus fruits seems to have been the main object, food products, corn, vegetables, coffee, cacao, cattle, hogs and forage were not neglected. A few miles south is the colony of Bayate, settled very largely by Swedish Americans, whose programme has been quite a departure from that of other colonists in Cuba. Their children are being taught Spanish in the schools so that they may bring their parents more closely in contact with their Spanish speaking neighbors. There are approximately 200 settlers in this community, most of whom have devoted their energies to growing sugar cane, for which the land in the neighborhood is excellently adapted. The Auza mill, twelve miles further down the railroad, buys all of the cane they can raise, giving them in exchange 5½ lbs. of sugar for every 100 pounds of cane. There is a very decent little hotel, built of mahogany and cedar, furnishing accommodations to guests who may happen to stop. Bayate has its school house, for which the Cuban Government furnishes two teachers, one of whom teaches in Spanish and the other in English. Most of the settlers have their own cows, pigs and an abundance of chickens. Some of them are planting coffee and cacao on the hill sides. Two
  • 80. crops of corn may be easily grown in this section, and nothing perhaps in Cuba, brings a better price, especially in the western end of the Island. It would seem quite probable that general farming will eventually take the place of the citrus fruit grove in Cuba, as a source of permanent income and profit. The demand for sugar, brought about by the European War, greatly increased the acreage of cane, and has undoubtedly saved many American colonies, especially those of Oriente, from economical disaster. It is to be hoped that the Cuban Government, in the future, may be induced to provide some kind of supervision over projected colonies in regard to the selection of localities, the character of soil, and the election of agricultural undertakings which will insure success. It is the desire of the Government that all homeseekers, if possible, may find life in Cuba both pleasant and profitable, and only in some such way can the mistakes of colonization in the past be avoided.
  • 81. INDEX A, B, C, D, F, G, H, I, M, O, P, R, S, T, V, W, Y. Agramonte, General Eugenio Sanchez, Secretary of Agriculture, 154. Agriculture, 144; typical rural home view, 145; natural advantages of soil and climate, 145; Department of Agriculture, 148; Division of Agriculture, 148; of Commerce, 149; of Veterinary Science and Animal Industry, 149; of Forestry and Mines, 149; of Trade Marks and Patents, 150; of Meteorology, 150; of Immigration, Colonization and Labor, 150; of Game and Bird Protection, 151; of Publicity and Exchanges, 152; Experiment Station, 153; breeding live stock, 155; fruits and vegetables, 156; combatting insects and diseases, 157; “black fly,” 157. See Grains, Grass, Fruit, Vegetables, Stock-Raising. American Colonists, 80, 103, 390; deluded by speculators, 391; ill-chosen sites, 391; La Gloria, 392; relations with the Cubans, 392; increasing and assured prosperity for those who persevere, 393; Isle of Pines, 394; Herradura, Pinar del Rio, 396; Bartle, 398; Victoria de las Tunas, 399; Omaja, 399; Paso Estancia and Bayate, 400.
  • 82. American Legation at Havana, 298. Animals, Indigenous, 257; the hutia, 257; sandhill crane, 258; guinea fowl, 258; turkey, 259; quail, 259; buzzard, 259; sparrow hawk, 259; mocking bird, 259; pigeons, 259; parrots, 260; tody, 260; orioles, 260; lizard cuckoo, 261; trogon, 261; flamingo, 262; Sevilla, 262; ani, 262. See Poultry, Stock Raising, Bees. Asphalt and Petroleum:, 126; early discovery of pitch, 126; observations of Alexander von Humboldt, 127; in Havana Province, 128; in Matanzas, 128; in Pinar del Rio, 129; many wells sunk, 130, et seq. Atkins, Edward F., Sugar promoter, 177. Banking. See Money and Banking. Bees, for honey and wax, 280; exceptional facilities for culture, 281; trade in wax, 282. Birds. See Animals. Botanic Gardens, 301. Cacao, 233;
  • 83. for food and drink, 234; varieties, 236; culture, 236. Camaguey Province, 71; history, 71; topography, 74; harbor of Nuevitas, 78; resources and industries, 79; American colonies, 80; Camaguey City, 82; chrome deposits, 116. Canning, opportunity for industry, in pineapples, 226. Cardenas, City, 56; City Hall and Plaza, scene, 56; Industries, 57; mines, 58. Cauto River, 85. Chocolate. See Cacao. Chrome. Sec Mines and Mining. Cienaga de Zapata, 67; plans for draining, 165. Cienfuegos, 65. Clay and Cement, 27. Climate, 19; equable temperature, 19; rainfall, 20; at Havana, 31. Cocoa. See Cacao. Coffee, 197; origin of Cuban plantations, 197; many abandoned groves, 198; methods of culture, 199; profits of crop, 199; marketing, 200; encouragement for the industry, 201. Commerce. See Ocean Transportation, and Railroads. Cork Palm, 38. Customs. See Ocean Transportation.
  • 84. Drives: A Paradise of Palm-shaded automobile highways, 326; roads radiating from Havana, 327; to Matanzas, 328; to Artemisa, 328; to Candelaria, 329; San Cristobal, 329; Bahia Honda, 320; San Diego de los Banos, 330; Pinar del Rio, 331; Valley of Vinales, 331; Mariel, 333; radiating from Matanzas, 335; Cardenas, 336; Cienfuegos, 336; Trinidad, 336; radiating from Santa Clara, 337; Camaguey, 337; Santiago, 337; among Mountains of Oriente, 338. Forestry, 135; great number and variety of trees, 135; alphabetical list of sixty leading kinds, with characteristics of each, 136, et seq.; location of timber lands, 142; extent, 143. Fruits: Aguacate, 228; varieties, 229; for salads, 230. Anon, or sugar apple, 226. Bananas, the world’s greatest fruit, 219; methods of use, 219; grown for commerce, 220; soil and cultivation, 221; varieties, 222; possibilities of the crop, 223. Chirimoya, 226.
  • 85. Citrus fruits, 211; orange groves, 212; discretion and care needed in culture, 214; varieties of oranges, 215; grape fruit, 217; limes, 217. Figs, 228. Grapes, 232; experiments with various kinds, 233; wine-making, 233. Guava, 228. Mamey, 227. Mamoncillo, 228. Mango, foremost fruit of Cuba, 203; the Manga, 204; varieties and characteristics, 204, et seq.; for both fruit and shade, 209; fruit vender in Havana, scene, 209. Pineapples, 224; soil and culture, 224; profits of crop, 225; varieties, 225; for canning, 226. Sapodilla, see Zapote. Tamarind, 227. Zapote, 226. Grain: Indian corn, 248; Kaffir corn, 249; millet, 249; wheat, 249; rice, 250; opportunities for rice culture, 251. Grasses and Forage Plants: Parana grass, 253; Bermuda grass, 253; alfalfa, 253; cow peas, 254; beans, 255; peanuts, 255.
  • 86. Guantanamo, 89. Harbors: Havana, 28, 342; Mariel, 41, 341; Cabanas, 42, 341; Bahia Honda, 42, 341; Cienfuegos, 65, 349; Nuevitas, 78, 345; Nipe, 87, 346; Guantanamo, 89, 347; Santiago, 87, 348; Matanzas, 343; Cardenas, 344; Sagua, 344; Caibarien, 344; Manati, 345; Puerto Padre, 346; Banes, 346; Cabonico and Levisa, 347; Sagua de Tanamo, 347; Baracoa, 347; Manzanillo, 349; Batabano, 350. Minor harbors, 350, et seq. Hawley, Robert B., Sugar promoter, 175. Havana, City: history, 303; famous streets and buildings, 304 et seq.; modern development of city and suburbs, 307; El Vedado, 308; places of Interest, 309; National Theatre, 310; the Prado, 310; parks, 211; Colon Cemetery, 311; Municipal Band and other musical organizations, 312; Conservatory of Music, 312;
  • 87. drives, 313; bathing beaches, 313, 314; Havana Yacht Club, 314; fishing, 314; Jai Alai, 315; baseball, 316; horse racing, 317; golf, 317; the Templete, 317; the Maestranza, 318; Department of Sanitation, 318; La Hacienda, 319; old Governor-General’s palace, 319; Senate Chamber, 320; “General Wood Laboratory,” 321; School of Industrial Arts and Sciences, 322; Academy of Sciences and Fine Arts, 322; President’s Palace, 322; new Capitol, 324; National Hospital 325. See Places of Historical Interest. Havana, Province: topography, 21; Valley of the Guines, 23; tobacco region, 24; forests, 25; agriculture and horticulture, 26; industries, 27; harbor of Havana, 28; water supply, 30; climate, 31. Henequen: world-wide importance, 53; brought from Yucatan, 190; first plantation, 191; International Harvester Company’s plantation, 191; possibilities of extension of the industry, 192; advantages of soil and climate, 193; estimates of cost and profit, 195.
  • 88. Himely, H. A., estimates Sugar crop, 166. Holguin, 93. Iron. See Mines and Mining. Magotes, 14. Manganese. See Mines and Mining. Manzanillo, 92. Matanzas Province: Topography, 49; drainage system, 49; Yumuri River and Valley, 51; resources, 52; henequen and sisal, 53; Matanzas City, 54; Caves of Bellamar, 55; Cardenas, 56; mines, 58; sugar, 58; chrome, 116. Menocal, Mario G., Sugar promoter, 175. Mines and Mining: Pinar del Rio, 47; Matanzas, 58; Oriente, 96; early search for gold, 104. Copper: El Cobre mines, 105; near Havana, 106; Bayamo, 107; Matanzas, 108; Santa Clara, 108; Camaguey, 108; Pinar del Rio, 109; American interests in, 109; Matahambre mines, 110. Iron, in Oriente, 111; Camaguey, 112; Pinar del Rio, 112; nickeliferous ores, 112;
  • 89. statistics of shipments of iron and copper ores, 112. Manganese, in Oriente, Pinar del Rio and Santa Clara, 115, 120, 121, 122; analysis of ore, 123; output, 124. Chrome, in Havana, Matanzas, Camaguey and Oriente, 115; United States Geological Survey’s prospects, 114, 117; many rich deposits, 117 et seq. Money and Banking: Early monetary systems, 361; double standard adopted, 363; stabilization under American occupation, 363; present standard and unit, 364; statistics, 364; list of principal banks of Cuba, 366. Ocean Transportation: United Fruit Company, origin of, 376; Lorenzo D. Baker and Andrew D. Preston, 377; Minor C. Keith’s Costa Rica railroad, 378; development of world’s greatest agricultural transportation company, 379; magnitude of its fleet, 379. New York and Cuba Mail Company, origin and development of, 380; Ward, Alexandria and other lines merged, 381; extent of service, 381 et seq.; its fleet, 382. Munson Steamship Line, 383; extent of its service, 383. Peninsular and Occidental Steamship Company, 383; its great ocean and railroad ferry from Havana to Key West, 384. Pinillos Izquiendo Line, between Cuba and Spain, 384; its large fleet, 385. Southern Pacific, formerly Morgan, Line, 385. French Line, 385; its fleet, 386. Japanese Line, Osaka Shosen Kaisha, 386. Customs regulations, 387; invoices, 387; consular fees, 389;
  • 90. Cuban consulates in United States and its territories, 389. Organ Mountains, 13. Oriente Province: Topography, 83; picture of mountain road, 84; rivers, 85; sugar, 86; Guantanamo, 89; Santiago, 89; resources and industries, 95; mines, 96; iron, 110; chrome and manganese, 117. Packing Houses, opportunity for, 273. “Paradise of Palm Drives,” 326. People of Cuba: Their hospitality and other traits, 1; domestic habits, 2; racial descent, 3; Gallegos and Catalans, 5; English, 5; Irish, 6; Italians, 6; Germans, 7; Americans, 7. Petroleum. See Asphalt. Pinar Del Rio Province: Topography, 34; Valley of Vinales, 36; harbors, 41; Pinar del Rio City, 45; Vuelta Abajo tobacco region, 45; mines, 47. Places of Historic Interest, 284-302: Atares Fort, 300; Bayamo, 92; Belen Convent and College, 298; Bellamar Caves, 55; Cabanas, la, 286;
  • 91. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com