hide - Understanding jQuery
hide - Understanding jQuery
hide - Understanding jQuery
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
“<br />
Second Revision. July 2012<br />
<strong>Understanding</strong><br />
<strong>jQuery</strong><br />
In Detail<br />
An almost poetic guide to a broader<br />
understanding of web development<br />
concepts and creating dynamic web<br />
applications.<br />
Includes an Interactive Table of Contents,<br />
improved JavaScript chapters, 20+ pages of new content<br />
practical <strong>jQuery</strong> lessons and Regular Expressions<br />
2012 Greg Sidelnikov greg.sidelnikov@gmail.com<br />
PHP & MySQL<br />
database library class<br />
See page 39.<br />
1
About the Book<br />
Table of Contents<br />
Credits and Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1<br />
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2<br />
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3<br />
Pre-flight<br />
A Lesson in Creativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4<br />
Thinking About Creating Websites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5<br />
Logical vs. Intuitive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7<br />
Moving External SCRIPT Files to the Bottom of the Page. . . . . . . . . . . . . . . . . . . . . . . . 9<br />
Determining the Placement of Internal JavaScript Code. . . . . . . . . . . . . . . . . . . . . . . . 10<br />
JavaScript Boot Camp<br />
The Importance of <strong>Understanding</strong> JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11<br />
JavaScript Boot Camp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13<br />
What is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14<br />
Where to Place JavaScript Code?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15<br />
Everything is an Object. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15<br />
Functions as Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17<br />
Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19<br />
Global Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19<br />
Function Closures - What Are They? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20<br />
What Exactly is a JavaScript Variable? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23<br />
Are They Variables or Objects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23<br />
Determining Variable Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24<br />
Variable Data Storage, Memory and Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25<br />
What is a Variable?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29<br />
Bitwise Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30<br />
<strong>Understanding</strong> JSON Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34<br />
Ajax, PHP and MySQL<br />
Making HTTP Requests with Ajax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36<br />
What are some of the things that Ajax can be used for?. . . . . . . . . . . . . . . . . . . . . . . . . 37<br />
Inserting Form Values into MySQL Database on Submit . . . . . . . . . . . . . . . . . . . . . . . 39<br />
Ajax: In Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41<br />
2
Prototype, JavaScript Objects and JSON<br />
Javascript as a Prototype-based Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42<br />
Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42<br />
Dynamic Prototype-based Objects in JavaScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45<br />
The this Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46<br />
Creating a JavaScript Object Using JSON. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47<br />
More About JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49<br />
Everything in JavaScript is an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50<br />
Compile Time and Run Time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50<br />
Prototype. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51<br />
Learning JavaScript Object Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52<br />
Are Variables Objects?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54<br />
Using typeof in a Real-World Scenario. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56<br />
<strong>jQuery</strong><br />
Learning <strong>jQuery</strong>. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59<br />
What is JavaScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60<br />
What Makes <strong>jQuery</strong> Worth Studying? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61<br />
Including <strong>jQuery</strong> In Your Webpage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62<br />
Where Do You Type <strong>jQuery</strong> Code?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62<br />
Web App Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63<br />
Calling <strong>jQuery</strong> Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63<br />
<strong>jQuery</strong> as a JavaScript Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66<br />
The Basic Structure of <strong>jQuery</strong> Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66<br />
Web Application Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68<br />
Including <strong>jQuery</strong> In Your Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69<br />
Including <strong>jQuery</strong> as an External CDN-based Files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71<br />
How To Always Include the Latest Version of <strong>jQuery</strong> . . . . . . . . . . . . . . . . . . . . . . . . . . 72<br />
Including <strong>jQuery</strong> UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73<br />
CSS Selectors<br />
CSS Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74<br />
What Kind of Elements Can You Select? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75<br />
Common CSS Selector Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76<br />
CSS Selector Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77<br />
Using Colon-based CSS Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79<br />
I Selected an Element. What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79<br />
Making Complex Selections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83<br />
More About CSS Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85<br />
Selecting Things: A Bird’s Eye View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85<br />
3
Get in the Habit of Using Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87<br />
Whose Children Are These?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88<br />
Using :nth-child Selector. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88<br />
A Small Detail About Using :nth-child Selector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89<br />
First and Last Children . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90<br />
Selecting by “empty” Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91<br />
Hidden or Visible. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91<br />
Even or Odd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91<br />
<strong>jQuery</strong> Events<br />
<strong>jQuery</strong> Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92<br />
Two ways of attaching an event handler to an event. . . . . . . . . . . . . . . . . . . . . . . . . . . . 93<br />
How to Unbind an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93<br />
Using toggle() Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96<br />
What is Event Capture and Event Bubbling? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96<br />
Event Capture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97<br />
Event Bubbling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97<br />
List of All <strong>jQuery</strong> Events. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97<br />
Speeding Up <strong>jQuery</strong><br />
The first rule of Javascript Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98<br />
The second rule of Javascript Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100<br />
Choosing the Right Context. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .100<br />
Practical Lessons<br />
Practical <strong>jQuery</strong> Lessons. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102<br />
Lesson 1: The :not Selector.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102<br />
Lesson 2: Storing Data Inside HTML Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .106<br />
Lesson 3: Callback Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108<br />
Lesson 4: Using append and prepend methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .108<br />
Lesson 5: Using appendTo and prependTo methods . . . . . . . . . . . . . . . . . . . . . . . . . .109<br />
Regular Expressions<br />
Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .111<br />
Using the RegExp object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113<br />
Rules of the Pattern Parameter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .114<br />
Matching the Target String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .115<br />
Regular Expression Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .118<br />
Final Note from the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120<br />
4
Thought transcends matter.<br />
When we looked inside an atom we found what we imagined would be<br />
there. We also found smaller particles inside molecules when we looked.<br />
We found exactly what we were looking for in the first place.<br />
When we looked outside into the universe and into the infinite vastness<br />
of space we found that it was expanding even faster.<br />
I hope you agree that according to these observations it seems that we<br />
often find that which we already believe to be there.<br />
The fact that you have purchased this book indicates that you believe you<br />
will learn something new.<br />
When I was writing it I believed the same thing.<br />
Greg Sidelnikov<br />
greg.sidelnikov@gmail.com<br />
5
Credits and Acknowledgements<br />
This book has been written over a long period of time with the help of many volunteer idea<br />
contributors. I am thankful for the support I have received from the subscribers to my <strong>jQuery</strong><br />
Tutorial Newsletter, the cornerstone and the turning point for writing this book.<br />
As I was writing the book I have frequently shared the excerpts with my newsletter subscribers.<br />
I have received feedback ranging from syntax and spelling corrections to requests for making<br />
significant clarifications and source code improvements.<br />
If you have contributed in the past and would like to appear on this list, please send me your<br />
name, email address, your website (or social network link) and and an attachment of your contributions<br />
in a text file.<br />
Name Contribution<br />
Yonghui Song<br />
s_yh@hotmail.com<br />
Link correction, document layout improvements, requests to increase<br />
the depth of the JavaScript Bootcamp section, function closure<br />
diagram correction (as also pointed out by many others. Thanks!)<br />
I am thankful for having the support of these volunteer editors. Just because I am writing the<br />
book doesn’t mean someone else couldn’t possibly help me. On the contrary, anyone is welcome<br />
to make a contribution.<br />
Electronic pusblishing format gives me the ability to update the book at any time. If you would<br />
like to make a contribution please email me at greg.sidelnikov@gmail.com<br />
1
Preface<br />
The purpose of this book is to provide a sufficient amount of educational material to the passionate<br />
person who is interested in learning more about creating dynamic websites. Perhaps<br />
you have already studied HTML in the past and now you are curious about getting better at<br />
adding dynamic elements to your web pages. Or perhaps you want to add features to one of<br />
those big website projects that require a deeper understanding of JavaScript and <strong>jQuery</strong>.<br />
<strong>jQuery</strong> is not a programming language. It is a library of functions written in the language<br />
called JavaScript. In order to understand <strong>jQuery</strong> we must also understand JavaScript. On the<br />
other hand, just to get started it is not necessary to know everything about JavaScript. This is<br />
why much time was spent picking the gems out during the process of determining the subjects<br />
to be included in this book.<br />
This book was designed with education as number one priority. It was organized in such a way<br />
that it can be thought of as a collection of principles and tutorials written to help web designers<br />
and web developers reach a deeper understanding of creating websites.<br />
Throughout the book practical examples are shown along with the solutions using <strong>jQuery</strong><br />
functions. Readers will get a solid review of most important concepts behind JavaScript programming.<br />
An example of that would be attaching events to HTML elements which is explained<br />
using both JavaScript and <strong>jQuery</strong>.<br />
Even though this book offers a deep review of <strong>jQuery</strong> functionality, instead of looking at it<br />
merely as a <strong>jQuery</strong> manual or a list of all <strong>jQuery</strong> functions, it would probably be better to see<br />
it as a course covering a diverse set of website creation subjects. After reading this book you<br />
will learn about proper web page construction from scratch, creating clickable CSS buttons,<br />
selecting HTML elements using powerful <strong>jQuery</strong> selector syntax and much more. In other<br />
words, the focus of this book lies on both: web design and web development. The popularity of<br />
<strong>jQuery</strong> has a lot to do with offering functions and methods to work on both of these fronts.<br />
This book is for many different kinds of audiences. In order to suit both beginners and skilled<br />
programmers, complex subjects are described using simple language; because experts already<br />
understand these subjects in depth and need a simple overview, and simple subjects are described<br />
using additional detail; because beginners are looking for in-depth information.<br />
On the next page we will go over a few details that will help you understand the presentation<br />
format of this book and make it easier for you to go through the book.<br />
2
Introduction<br />
What’s an educational book anyway? Any educational book is like an airport runway. It’s gets<br />
you somewhere. After reading this book you will be ready to continue experimenting with<br />
new knowledge and discover things that are not even mentioned in the book itself. I believe<br />
the function of any educational material is to give direction.<br />
The soul of a book can be found in the content it will encompass. Choosing the content for<br />
this book has been a tremendously time consuming task. Designed as a tool for education this<br />
book gives you enough information to move you forward and become a better JavaScript programmer<br />
and web designer.<br />
Even though very simple examples are used throughout the length of this book, it does not<br />
mean that this book has no value to someone with an advanced understanding of JavaScript.<br />
Simple tutorials are much more potent than elaborate ones.<br />
This book is for anyone who wants to learn <strong>jQuery</strong> and JavaScript. It is also an invitation to<br />
start taking a look at things from a slightly different perspective. I believe programmers of<br />
any skill level will find this book useful. Visual diagrams presented throughout the book are<br />
designed to help you memorize important concepts and in the end, reach the kind of understanding<br />
that would make you comfortable with creating your own dynamic websites and web<br />
applications.<br />
You can’t please everyone. But when making this book I believed that it was possible to make<br />
an intelligent attempt at creating a book which would be useful to beginners and experienced<br />
programmers, without having to make a big compromise. For this reason, while writing this<br />
book I have developed something I now refer to as the mirror technique.<br />
The Mirror Technique<br />
1. Simple subjects will be explained in great detail.<br />
2. Difficult subjects will be explained in intentionally simplified language.<br />
The requirement of learning JavaScript consists of understanding simple but also complex subjects.<br />
The mirror technique is a set of two rules with regard to complexity of material. Sticking<br />
to this logic, I managed to keep the content of this book neutral and increase audience appeal.<br />
This way everyone gets a little of everything and the book remains in a neutral zone. Still, it’s<br />
probably fair to say that this book is best suited for beginner-to-intermediate level programmers.<br />
I try to create a balance, but this is the group that will find this book helpful the most.<br />
In addition, over the years it has become apparent to me that most people who are looking for<br />
computer tutorials are beginners. So it’s wise to put a little more emphasis on writing for that<br />
group in particular.<br />
3
A Lesson in Creativity<br />
The web developer is responsible not only for writing code, but understanding the structure of<br />
the entire web application. Part of the creative process is understanding web application composition.<br />
The HTML, CSS and JavaScript files that go into a website.<br />
When it comes to creating a great work of art, whether it’s a website, an interactive computer<br />
simulation, a game, or anything that has to do with any programming language, the language<br />
itself is only half of the story. This is why it’s so important to be able to integrate yourself into<br />
this creative process rather than thinking in terms of writing the code.<br />
If you want to create extraordinary things, just understanding <strong>jQuery</strong> won’t matter. What will<br />
matter is how creative you are at finding new ways of putting things together. Knowing the<br />
basics of web application composition is also very important.<br />
I made this animation to demonstrate how little <strong>jQuery</strong> and JavaScript code is required to create<br />
something interesting.<br />
View this demo online:<br />
www.learnjquery.org/demos/3d-css.html<br />
Don’t worry if you don’t understand rendering using 3D CSS. We will cover 3D CSS later on in<br />
the book. But as you can see, interesting things can be made with little <strong>jQuery</strong> code.<br />
Study the composition of this application. If you don’t understand how that code works yet, no<br />
problem! This is what the rest of this book is all about.<br />
4
Thinking About Creating Websites<br />
Now that we understand the basics behind web application composition, let’s take a look at<br />
what else a web developer usually thinks about when creating an application or a website. As<br />
simple as it is, many decisions have gone into creating the Seaguls Detected demo.<br />
For example, finding a good cloud texture was important. Another crucial detail was choosing<br />
the 3D angles for the sky and the ground. In this case in particular I had to think in 3D.<br />
Change the angle by a few degrees higher or lower, and it doesn’t look right anymore.<br />
But <strong>jQuery</strong>’s simple syntax was instrumental in making adjustments quickly, which eventually<br />
led to the final version of the code. If we don’t count creating the graphic used in this demo, it<br />
would only take us about an hour or so to write the code.<br />
The <strong>jQuery</strong> library simplifies JavaScript programming. It gives us an easier syntax and an access<br />
to functions that make it easy to get things done. For example, to move an HTML element<br />
such as DIV with id “box“ to a new position on the screen the <strong>jQuery</strong> command would be:<br />
<strong>jQuery</strong> Object<br />
CSS Selector<br />
<strong>jQuery</strong>(‘div#box’).css(‘left’, ‘100px’);<br />
<strong>jQuery</strong> function<br />
HTML element attribute<br />
New position<br />
<strong>jQuery</strong> has a very simple syntax and a set of powerful CSS selectors. They allow us to elegantly<br />
select any set of HTML elements and then execute some type of a function on that selection.<br />
Would you like to rotate all DIV elements on your page? Just one? Or would you like to change<br />
the background color of all INPUT elements to black? How long should this animation last?<br />
This it the type of thinking that is involved in adding dynamic features to your website using<br />
the <strong>jQuery</strong> library.<br />
How fast should the background image scroll to simulate the “flying through space” effect?<br />
When to start or stop seagull animation? All these are the questions that can only be answered<br />
by approaching the problem with a great deal of intuitive thinking. And <strong>jQuery</strong> makes the wall<br />
between writing code and creativity thinner.<br />
In order to create this demo I used the code as a paintbrush, not as a monotone logical process.<br />
I envisioned the results based on my knowledge of <strong>jQuery</strong>, which allowed me to create<br />
dramatic animations with just a few lines of code.<br />
5
I love <strong>jQuery</strong> because it allows me to make fast decisions. How many lines of code would I<br />
need to write in JavaScript in order to achieve these effects? More than I would like to. This<br />
minimalist nature of <strong>jQuery</strong> syntax helps us become much more efficient at getting things<br />
done.<br />
It also gives me an assurance that the code written just once will run in more than one browser.<br />
<strong>jQuery</strong> is an ideal framework for creative projects. Especially ones that you need to complete<br />
and test quickly.<br />
The decisions such as the ones that went into “Seagulls Detected” demo, the outcome of which<br />
is a dramatic visual effect, really transcend the results of your work as a programmer. The end<br />
result becomes much greater than just the code, which, in isolation, seems monotone and boring.<br />
People who write code are not machines. But they can be, if they look at programming as just<br />
writing the code. But there is also a human element. Exercising your creative thought and putting<br />
ideas into action will determine quality of your work.<br />
It is this type of thinking I recommend that you look into developing. I hope that by the end of<br />
reading this book I have inspired you to see things using the creative approach.<br />
It’s important to understand this. Don’t try to think that the tools you are using will be the<br />
ones responsible for the quality of your work. Try to see how you can improve yourself, your<br />
creativity and your knowledge. And the quality of the results will improve as well.<br />
The <strong>jQuery</strong> code for this demo is incredibly compact – just under 100 lines you can see in the<br />
source code below. Yet it creates so much. This is the power behind <strong>jQuery</strong> that will allow you<br />
to create your own websites and games with less code.<br />
To see the entire source code of the “Seagulls Detected” demo<br />
copy this hyperlink into your browser’s address bar:<br />
view-source:http://www.learnjquery.org/demos/3d-css.html<br />
To harness the power of <strong>jQuery</strong>, you don’t have to know everything about it. You just need to<br />
know the most powerful CSS selectors and functions. Also you will need to know about the<br />
order in which to pass arguments to these functions.<br />
Even learning just a few key principles will make a powerful impact on your ability to become<br />
much more efficient at creating dynamic websites, games or applications. Try to memorize<br />
them once you find them in this book. Create your own demos to see what different <strong>jQuery</strong><br />
functions do. Experiment. Don’t copy and paste code. Challenge your creativity.<br />
6
Logical vs. Intuitive<br />
What is your programming method? Do you care about formatting your code more than the<br />
results it produces on the screen? Four spaces before each statement or two? Should I use tabs<br />
instead of space bar to space my code? Probably not.<br />
After making modifications to parameters that are to do with screen space, how good are you<br />
at visualizing the true distance between 100px and 150px when you finally hit refresh and it<br />
is actually rendered on the screen? How many times will you hit refresh before the layout is<br />
aligned and is pixel-perfect?<br />
Web designers who are also web developers usually write code while simultaneously envisioning<br />
what the outcome of that code is going to be on the screen. The result is a visualization of<br />
computer code they have written. It’s like they paint with computer commands and the language<br />
is their paintbrush.<br />
That’s what I love about web development. It forges a connection between the logic and visualization<br />
of the outcome. It also has a great deal to do with the intuitive process. Web development<br />
and programming don’t need to be excluded from it.<br />
But let’s not fool ourselves. Writing code can also be a great exercise in logic. And it’s not always<br />
fun and games.<br />
Luckily, many <strong>jQuery</strong> plug-ins and JavaScript functions have already been written. Don’t hesitate<br />
to use other people’s work. Don’t forget to give them credit. In the end, what matters is the<br />
result... your work, what is perceived by the person who is using your software.<br />
In the end, nobody cares about how you made something. People care only about the experience<br />
of using your software. I will put my best effort into explaining the how in this book. The<br />
what is up to you.<br />
I hope that you will find my approach to explaining concepts that are mostly, or even entirely<br />
logical, easy to follow. My goal in such cases is to always break down the problem into small<br />
pieces.<br />
7
Improving Page Load Performance<br />
The subject of page load optimization is comprehensive. An entire book could be written just<br />
about that. In fact Steve Souders had written such a book. It’s called High Performance Web<br />
Sites.<br />
He also has a phenomenal website www.stevesouders.com where you can find much more<br />
about the process of optimizing your website as it’s being downloaded.<br />
We already discussed the basic HTML page structure. There are some things you can do to<br />
optimize your site. But it’s not always easy to know whether you’re making the right choice.<br />
What if some browsers don’t support a technique that is not documented? What if inserting<br />
JavaScript at the wrong place in your page slows performance? It can happen.<br />
There has been a fair deal of debate about whether moving JavaScript code to the very bottom<br />
of your HTML page is a good idea or not. The answer is that in some cases it is, in others it’s<br />
not. In many cases, it is the right thing to do.<br />
In order to understand this, let’s first analyze what the developers of HTML themselves can tell<br />
us about this issue. Let’s see what the original HTML specification tells us:<br />
http://www.w3.org/TR/1999/REC-html401-19991224/sgml/dtd.html<br />
In other words, this is what it tells us:<br />
1. SCRIPT is allowed directly inside the BODY tag<br />
2. Directly inside HEAD (of course)<br />
3. Directly inside BLOCKQUOTE<br />
4. Directly inside FORM<br />
5. Within inline elements, which includes: span, sub, sup, a, p and the list goes on.<br />
And there are many other rules.<br />
We’re not interested in JavaScript code in inline elements right now. Of course you can use<br />
JavaScript there inside HTML attributes like onclick or onmouseover.<br />
Number 1 is of most concern to us. If SCRIPT tag is allowed inside BODY tag, that means that<br />
it is also allowed at the very bottom of the page right before closing the /BODY tag. This can<br />
be helpful.<br />
But wait. It may not always be a good idea to simply move all of your JavaScript code or files<br />
to the bottom of the page. In some cases doing this may actually make your page load slower.<br />
Next page will briefly outline some details you should know.<br />
8
Moving External SCRIPT Files to the Bottom of the Page.<br />
In contrast to a program that executes as a series of functions, one after another, a website is<br />
governed by real-time events that execute at irregular intervals which cannot always be relied<br />
on to occur in the same order.<br />
This unpredictable manner in which each part of your website executes contributes to the confusion<br />
around the subject of choosing the proper location for SCRIPT tags and the files they<br />
specify within the SRC attribute.<br />
If you put your SCRIPT tags at the very end of the page, it is possible that a user may see part<br />
of the page including an element, such as an HTML button, with a JavaScript function call<br />
defined in SCRIPT tags that have not been loaded yet - because they are at the bottom of the<br />
page in the first place.<br />
Externally defined JavaScript files could be hosted somewhere else, or on your own web host<br />
that may stutter for a moment. You have probably already witnessed this before that sometimes<br />
HTTP requests take time, stalling the entire web-page. This can occur regardless of<br />
whether your SCRIPT file is located within the HEAD tag or at the bottom of the page just<br />
before the closing /BODY tag.<br />
This can happen even on a fast host server, especially one that is not configured for receiving<br />
and processing a sufficient number of HTTP requests per second. Browser design should also<br />
be taken in consideration.<br />
Remember that every single time you add a new SCRIPT tag with a SRC location, a new<br />
HTTP request will be created for that page. What will happen if, when we include external<br />
files at the bottom of the page, that these requests take longer to load than the HTML page<br />
itself?<br />
Imagine that you have HTML button on a page. A SCRIPT tag which includes a file linking to<br />
the definition of this button’s function is now placed to the bottom of the page. Now that it is at<br />
the bottom, the page will indeed load faster, but HTTP requests still have to execute. The page<br />
HTML has finished loading, but the JavaScript code containing your button functionality is<br />
yet to be loaded.<br />
What can we expect in a situation such as this? The result is that the user pushes a button<br />
whose functionality is still loading from those HTTP requests. The user gets a JavaScript error<br />
message, because the browser can’t find the script yet.<br />
The general guideline, therefore, is that unless there is a good reason to do otherwise, place<br />
your SCRIPT tags containing important on-page functionality inside the HEAD tag. All<br />
others can go to the bottom.<br />
9
Determining the Placement of Internal JavaScript Code<br />
There are cases when you want to use JavaScript code directly inside the page. You are probably<br />
already familiar with Google Analytics which offers statistics tracking JavaScript code.<br />
They recommend that you place this code right before the closing /BODY tag. This is different<br />
from SCRIPT tags.<br />
In this context it is absolutely reasonable, and even necessary, to place your code in a place toward<br />
the end of the page if you are interested in decreasing the perceived time it takes for your<br />
page to load.<br />
It’s convenient in this case because of the context in which the code is used. The HTTP requests<br />
are still being made, but only when the loading process reaches the bottom of the page.<br />
Google Analytics should not consider a page as being finished loading completely unless the<br />
bottom of the page has been reached. And it has nothing to do with on-page elements. This<br />
code does not affect any HTML markup. In this context it works.<br />
* * *<br />
External .js files that are not related to the functionality of on-page elements that are currently<br />
being loaded can be moved to the bottom. When you have DHTML features that are unlikely<br />
to be manipulated until after the page loads and renders (such as menus that are hidden by default,)<br />
moving the corresponding JavaScript code to the bottom of the page is the best solution.<br />
If, on the other hand, you have internal JavaScript code that is part of rendering the page, like<br />
drawing on canvas, then I recommend moving the external script into the HTML document<br />
and placing it right above the related HTML elements.<br />
Note that for high-performance, high-traffic web applications, these rules may change. Sometimes<br />
you just have to use knowledge of your web application in order to figure out the best<br />
placement for your JavaScript code.<br />
When trying to optimize your own website for page load performance, think about the context<br />
in which your JavaScript code is being used.<br />
This should help you understand the ideal place for your SCRIPT tags, whether it is at the<br />
bottom of the page, right before an on-page element that requires that code or inside the<br />
HEAD tag.<br />
Profile your code. Use tools like Google Chrome’s JavaScript Console to determine whether<br />
the changes you have made increase or decrease your page load time.<br />
10
The Importance of <strong>Understanding</strong> JavaScript<br />
<strong>jQuery</strong> is written in JavaScript. It is therefore important to understand at least some basic<br />
principles required for writing JavaScript code. You can understand people who are quick to<br />
jump into fiddling with <strong>jQuery</strong> right away because <strong>jQuery</strong> syntax is so easy to learn. But this is<br />
probably not a good idea.<br />
It would still be possible to start using <strong>jQuery</strong> without knowing these JavaScript principles but<br />
I don’t recommend it. If we don’t know what a nameless function and events are, how could<br />
we hope to understand the following statements that are so often seen in <strong>jQuery</strong>?<br />
$(document).ready(function(){ ... });<br />
(function($){ ... })(<strong>jQuery</strong>);<br />
In the following JavaScript chapters we won’t cover all aspects of JavaScript. The focus will be<br />
only on the most important concepts that relate to <strong>jQuery</strong> programming. Knowing what objects<br />
are is an incredibly important concept. Also, understanding the diversity of definitions<br />
and different ways in which JavaScript allows us to build our program becomes important.<br />
Some people jump into <strong>jQuery</strong> programming head first, without knowing anything at all about<br />
JavaScript. Try to avoid doing that. Instead, focus on understanding the concepts explained<br />
in the following book sections and once armed with this knowledge I guarantee that you will<br />
have a better grasp on <strong>jQuery</strong>.<br />
Most of the time these techniques will probably work, even if your code is being written in a<br />
completely wrong way. This is largely due to the great flexibility we are offered by programming<br />
languages designed for web development. But eventually you will want to update your<br />
code, or add something to it. And that’s when bigger problems will be introduced.<br />
Actually understanding the code that you write has a positive effect on increasing productivity.<br />
Moreover, proper code is fun to write because understanding the rules gives you the power to<br />
write great programs that work exactly in the way you want them to.<br />
You may continue pursuing to study JavaScript after you finish reading this book. You can<br />
browse through all available functions and definitions of JavaScript but it’s likely that you’re to<br />
never use some of any of them at all. This will depend on the needs of your website or web application<br />
project.<br />
The designers of any language or framework focus on the way in which it will be used by the<br />
user of that language (the programmer.) Sometimes a language feature can seem like a bug<br />
unless a mutual understanding is achieved between the programmer and the designers of that<br />
language. I hope that this book will become helpful in drawing that bridge.<br />
11
JavaScript<br />
1. The only language people start using without actually learning it.<br />
2. Probably the World’s most misunderstood programming language.<br />
Statements are According to Douglas Crockford:<br />
https://www.youtube.com/watch?v=hQVTIJBZook<br />
12
The goal of JavaScript Boot Camp, the next section of the book, is to focus your attention on<br />
the most important JavaScript concepts.<br />
The concepts you will learn from the pages are very basic. They are designed to get you up to<br />
speed in no time. Learn, understand and memorize them. Use this knowledge to increase efficiency<br />
of your work ethic as a web developer in your own projects.<br />
JavaScript Boot Camp<br />
Welcome to JavaScript boot camp. Who attends boot camps? People who want to quickly get<br />
up to speed with a set of basic ideas and become disciplined using them in practice.<br />
The content in the next chapter will go over some of the most important concepts of programming<br />
in JavaScript. It doesn’t pretend to be comprehensive by any definition of the word. The<br />
goal is to increase awareness of the most significant concepts in order to prepare you for understanding<br />
<strong>jQuery</strong>.<br />
13
What is JavaScript?<br />
Web designers use JavaScript to add dynamic function to websites. JavaScript can be used to<br />
manipulate position of HTML elements, validate web forms and create cookies. It’s a relatively<br />
easy language to learn. In the recent years JavaScript has gained increased popularity among<br />
larger circles of web developers.<br />
It is important to understand JavaScript now more than ever. As the web begins to rely more<br />
on dynamic functionality, interactive applications, HTML games and even 3D graphics in<br />
browsers, your knowledge of JavaScript and ability to use it in these situations determines your<br />
effectiveness as a web developer of dynamic web applications, user interfaces and websites.<br />
Before we go into exploring some of the fundamental JavaScript concepts, let’s take a brief look<br />
at what JavaScript is.<br />
JavaScript is a multi-paradigm programming language. The word paradigm takes its origin<br />
from the Greek word παράδειγμα (paradeigma.) It means a pattern. The phrase multi-paradigm<br />
programming language, then, is used in reference to a language that supports more than<br />
one code pattern, in other words, style.<br />
Some computer languages are designed with one type of a pattern, or paradigm, in mind. For<br />
example, a logical programming language such as Prolog was created strictly for working with<br />
mathematical equations. It is suitable for designing artificial intelligence algorithms.<br />
Other popular types of programming styles (or paradigms) include functional, object-oriented<br />
and event-driven, just to name a few. What’s important to understand is that computer<br />
programming languages can follow more than one paradigm and JavaScript is one of those<br />
languages. <strong>Understanding</strong> all programming paradigms is beyond the scope of this book, but<br />
it’s worth mentioning here because JavaScript supports a few of them.<br />
JavaScript was designed in order to be used in many different ways. JavaScript can be used as<br />
an object-oriented language (with limitations), as a functional language and as an event-driven<br />
language. It can probably be said that in a way JavaScript supports the logical paradigm too,<br />
because it provides a library stored in an object called Math, which is used for mathematical<br />
operations.<br />
Even though JavaScript supports some object-oriented programming principles it really is not<br />
an object-oriented programming language in itself. In fact, and even though everything in<br />
JavaScript is an object, people with C++ background would find JavaScript lacking some important<br />
object-oriented functionality they are used to, for example an easy way to work with<br />
concepts such as class inheritance (though not completely impossible) and interfaces.<br />
Still, objects play a large role in JavaScript functionality. Everything in JavaScript is an object.<br />
14
Where to Place JavaScript Code?<br />
In the section Improving Page Load Performance by Juggling Include Files we have briefly discussed<br />
JavaScript placement within an HTML page. Let’s go over it again because the following<br />
discussion will dive into source code examples.<br />
JavaScript code is written inside tags. It can also be written directly inside a separate<br />
file with .js extension, for example script.js is a popular one among web developers. External<br />
files like script.js only contain JavaScript code, not HTML or any other type of code. Internal<br />
instances of JavaScript are written directly into your HTML page. In both cases, JavaScript<br />
is added using the tag:<br />
1. To include an external JavaScript file, write this within the tag:<br />
<br />
2. To execute JavaScript code located directly inside an HTML page, write:<br />
alert(“Hello There.”);<br />
The code above will execute as it is being read at the location within your HTML page where<br />
you open and close your SCRIPT tags. In this example, the command alert(“Hello There.”);<br />
will execute. It will pop up an alert message box displaying the message “Hello There.”<br />
Everything is an Object<br />
An object is a concept in computer science that refers to an entity capable of being manipulated<br />
by the commands of a computer programming language. Even variables in JavaScript are<br />
objects.<br />
You may already be familiar with variables. A variable can be a numeric value such as 10, assigned<br />
to a literal name such as apples. For example, to create this variable you would write the<br />
following code:<br />
var apples = 10;<br />
It could be said that the variable called apple is assigned the value of 10. This variable in particular<br />
can also be called an integer, because it is assigned a numeric value. It would be possible<br />
to create a variable of type string by running the following code:<br />
var color = “green”;<br />
15
As you can see, variables can be assigned values of different types. For example strings or numbers,<br />
and there are others. A string is simply a collection of characters encased by two single<br />
or double quotes. You could have written var color = ‘green’; (notice the single quotes) and it<br />
would be an exact equivalent to the example above.<br />
But what the apples and color variables have in common is that both are objects in JavaScript.<br />
In the beginning of this section we determined that objects are entities that can be manipulated<br />
by commands of a programming language. What could be an example of this with regard to<br />
the two variables discussed above? Let’s first take a look at the basic behavior of variables and<br />
their values.<br />
You can rename the variable color, that has already been defined, from “green” to “red” by<br />
simply re-assigning the value like this:<br />
color = “red”;<br />
Note that we are no longer using the keyword var. The variable has already been created.<br />
However, even to create a variable in JavaScript, it is not necessary to use the var keyword in<br />
the first place. I do recommend, however, that every time you create a variable you use the var<br />
keyword. Consequent value re-assignment operations on this variable don’t have to include it.<br />
It’s also possible to assign a value of one variable to another. You can find out the length of the<br />
value stored in variable color by storing it in another variable len:<br />
var len = color.length;<br />
But wait, what is this dot? And where did length come from? The dot (.) operator is the access<br />
point for the properties of the variable, or object named color. You see, when we created the<br />
variable color, JavaScript created an entire object for us, which from the moment of its creation<br />
will also store its properties. These properties are determined by the internal definition of the<br />
string object in JavaScript.<br />
Interestingly, in addition to the properties created by JavaScript for these variables, we can also<br />
add our own properties to them. More on this later.<br />
When we assigned a string “red” to this variable, JavaScript automatically created an object of<br />
type String for us. Moreover, it counted the number of characters we typed and stored that<br />
number in the property called length.<br />
Also, in the earlier example where we created a variable called apples, an object of type Integer<br />
was created. All of this is done by JavaScript behind the scenes. We just use the syntax of JavaScript<br />
to manipulate these objects.<br />
16
It’s not important always necessary to understand that variables are actually objects. It is possible<br />
to write programs thinking of variables as variables. However, as you learn more and enable<br />
yourself to write more complex programs the knowledge of objects becomes important.<br />
Functions as Objects<br />
Even functions in JavaScript are objects. Below, we will consider the function add. add is the<br />
name of the function. You can also think of it as an object called add.<br />
Let’s consider this simple example:<br />
function add(a, b)<br />
{<br />
var result = a + b;<br />
return result;<br />
}<br />
This is a function definition. To define a function we start with the keyword function. This is<br />
followed by a custom name. The point of this function is to add two numbers. You are the one<br />
who determines the purpose, and therefore, the name of your new function.<br />
You will write the logic of the code of this function. In this example we are adding two numbers<br />
and return the result.<br />
Notice a and b in parenthesis just after the function name. These two values will be “passed” to<br />
the function at the time of program execution. Below you will see that I am passing the arbitrary<br />
numbers 10 and 5 to this function.<br />
Of course we are not limited to just two parameters. We could have just one paramter a or<br />
many more if required. Multiple parameters are separated by comma, so we have add(a, b).<br />
Within the function definition itself a and b are called parameters. We use these parameters to<br />
determine what this function will do with them. But when we execute the function, the actual<br />
values passed as parameters are called arguments. It’s easy to memorize because a parameter is<br />
always represented by one letter or word but an argument can be a statement like 1 + 2. In the<br />
example below 10 and 5 are this function’s arguments. They are passed as parameters a and b.<br />
var result = add(10, 5);<br />
By the time this statement finishes executing the variable result will store the return value of<br />
15 because 10 + 5 is 15. Inside the function, the value is returned using the return keyword.<br />
Notice that return is a reserved keyword. We cannot have a variable called return. In other<br />
words the code var return = 12; will generate a syntax error.<br />
17
The example above will first execute the function add and only then it will assign the returned<br />
value to the variable called result. Function add is executed with the two passed arguments:<br />
a=10 and b=5. The result, which is 15 will be then assigned to the variable called result.<br />
We read books written in English from left to right. We also write code from left to right and at<br />
first it appears to be natural to think that the first thing that happens is the value assignment to<br />
the variable result. But that’s not true. Logically, the function will execute first.<br />
It’s important to notice the direction of execution flow in a JavaScript statement. All code in<br />
a singled out statement is executed from right to left. The opposite direction in which it was<br />
written.<br />
In other words, the function add is executed first. The function calculates and returns a new<br />
value. Only then, this value is then assigned to the variable result.<br />
Notice that we can execute the function without variable assignment as in:<br />
add(10, 5);<br />
Notice the missing var result = assignment. The function would be executed in memory. No<br />
variable assignment would take place. But in this case in particular, it wouldn’t really make<br />
much sense because the function returns a value which is the main purpose of this function.<br />
In this case, the return value of the calculation 10 + 5 (or 15) would be returned but because<br />
we are not doing anything with it, the result will simply vanish. Often, the purpose of a function<br />
is to return a value but it depends on circumstances.<br />
A function doesn’t always have to return a value. It can be executed as a stand-alone block of<br />
code. An example of a function that doesn’t have to return a value is <strong>jQuery</strong>’s css or animate.<br />
These two function simply manipulate an HTML element on the screen.<br />
Functions and variables are the two of the most common building blocks of a JavaScript program.<br />
When learning <strong>jQuery</strong> you will notice that for the most part you will be calling functions<br />
that are already written. <strong>jQuery</strong> offers a number of interesting functions to work with the<br />
HTML code of your website.<br />
But before we get into <strong>jQuery</strong> there are still a few important concepts you need to understand.<br />
We will continue exploring these concepts throughout the JavaScript Bootcamp chapter.<br />
18
Scope<br />
In order to understand function closures, one of the next subjects in the book, you must first<br />
have an understanding of the concept of scope. Scope is where things are happening in your<br />
program. Scope is usually determined by the { and } brackets. For example, the function “add”<br />
we discussed earlier uses these brackets to define its scope. In other words, when the function<br />
is executed, what is executed is the code within that scope.<br />
We can call the function twice or three times, and again, over and over, the code contained<br />
in the scope of that function will be executed. When a function is executed, a special part of<br />
memory is allocated into which the function is loaded. Then this code is executed.<br />
Unfortunately, the low-level details of computer program execution flow is not a part of this<br />
book, and you don’t really need to know them to be a JavaScript or <strong>jQuery</strong> programmer. But<br />
it’s an interesting subject you may want to explore on your own.<br />
The most important concept you do have to understand with regard to scope, is that variables<br />
in a scope are not visible to other scopes in a program.<br />
What does not visible mean?<br />
For example, variables defined inside a function scope only work within that function’s scope.<br />
You can’t work with them from within other functions. That’s why variables can be passed to<br />
functions as parameters, instead.<br />
Most of the time, you will not be able to recall variables across scopes. In other words, the<br />
scope the variable was created in, is the only scope it can be used in. But there is an exception,<br />
and that is when we use a function closure, a concept we will define in a few moments.<br />
Remember that all variables in the global scope are visible from everywhere. The global scope<br />
is not limited to any brackets, it exists at the root of the program, “above” all other scopes.<br />
Global Scope<br />
Global scope is the root of your program. What you define in the global scope, things like<br />
functions, variables, arrays, and so forth... will be visible from anywhere inside your program,<br />
including, within all defined functions.<br />
Also, on the contrary, variables defined inside a function cannot be visible in the global scope,<br />
they are only visible within that function. Use scope to your advantage to organize data of your<br />
program. Many programmers don’t even know that the concept of scope exists, they just follow<br />
their instinct. There is nothing wrong with that. But being aware of it can be important if<br />
you are looking to improve your understanding of writing code efficiently.<br />
19
Only variables and events should be initialized inside $(document).ready, not functions.<br />
Though, this is not a rule! However, if you do that, certain things will occur that will prevent<br />
you from using the function in the global scope. In other words, function definitions are limited<br />
to the scope they are defined in, just like variables. We know that a scope is any place in<br />
your JavaScript program delimited by the { ... } brackets.<br />
I have received a question from one of my newsletters subscribers about defining a function<br />
inside $(document).ready(). It is an event that takes place after all DOM (all HTML elements)<br />
are physically loaded into the web page... so essentially what happens is that a function is defined<br />
inside the anonymous function that runs when this DOM event occurs. The function is<br />
now limited to the scope of the anonymous function attached to that event. Let’s take a look:<br />
<br />
$(document).ready(function()<br />
{<br />
function a() { alert(‘hello’); }<br />
a(); // here it works, because it was defined in the same scope<br />
}<br />
// But here it produces an error -<br />
// The function a() cannot be called outside of the scope it is defined in.<br />
a(); // error: undefined function<br />
<br />
In order to remedy this problem, we stick to defining all functions outside of the event This<br />
means they will become available to call from the entire program, even within $(document).<br />
ready... as well as throughout the whole scope of the program, the global scope.<br />
<br />
function a() { alert(‘hello’); } // let’s define the function in the global scope, instead.<br />
$(document).ready(function()<br />
{<br />
a(); // here it works<br />
}<br />
a(); // the function now works here as well<br />
<br />
20
Function Closures - What Are They?<br />
When working with any computer code for a long period of time, it is inevitable that you will<br />
come across situations when specific type of logic is required in order to solve a problem.<br />
Some of these situations are difficult to explain, unless you already understand the building<br />
blocks of a programming language. But don’t worry, these concepts only seem difficult at first.<br />
As you practice writing code these concepts will start to feel like a second nature.<br />
In computer programming languages, even outside of JavaScript, there are rules created by the<br />
developers of those languages that help us use all kinds of logical constructs that, in creative<br />
ways, help us write computer code. Sometimes programmers use these rules to create logical<br />
code structures. And sometimes they become adopted because they are so useful.<br />
What are function closures and why is it important to understand them?<br />
Remember that a closure can exist in any other language, not just JavaScript. It’s really just a<br />
concept. Unlike a variable, or an object, a closure is more like a theoretical concept rather than<br />
a feature of the language.<br />
As different languages do not always have a common definition of the lexical environment,<br />
their definitions of closure may also vary.<br />
Let me give you an example of a function closure in JavaScript and then we’ll take a look at<br />
what makes it special. Below is diagram that makes a visual connection between places in<br />
memory shared by the same objects (or variables).<br />
Flip over to the next page to see the diagram of the classic function closure pattern.<br />
21
Notice that variables a and b are created in global scope of the program, outside of the function.<br />
The actual assignment of these variables to a nameless function takes place inside the<br />
scope of the function foo(). This means that now, a and b refer to a memory address of a function<br />
within a function:<br />
Let’s call the function foo(); to assign the variables to functions. When we do this, the name of<br />
the variable itself becomes a function:<br />
a = function() { /* do something here*/ }<br />
After this assignment, calling the function is possible by just saying a(); What used to be a<br />
variable is now a function. In JavaScript it’s perfectly legal to reassign a variable to a new value,<br />
even if this new value is of type different from the type of the original variable. This is why it is<br />
often said that JavaScript data types are typeless. The type is not defined explicitly.<br />
As you can see, it’s possible to assign a variable to a function. Moreover, in this scenario<br />
the function doesn’t even have a name. What’s going on here? JavaScript allows us to create<br />
namesless functions. They are also known as anonymous functions.<br />
These anonymous functions are extremely useful when we need to create a function “on the<br />
fly” without having to define it prior to executing it.<br />
Using anonymous functions on the fly is a common technique. As you continue studying<br />
JavaScript you will find out that anonymous functions can be used in many different contexts.<br />
For now let’s focus again on the diagram explaining the function closure.<br />
22
Following the chart, you can see that the variables a and b are assigned to anonymous functions<br />
created within the scope of another function called foo(); When this happens, the variables<br />
in global scope will now actually be live references to the memory location inside foo();<br />
even after the function has finished executing.<br />
Calling a(); and b(); will execute the contents of the anonymous functions assigned to them<br />
within foo(); Remember that by simply defining foo(); these associates are not yet made. The<br />
function foo() must be executed at least to make these connections.<br />
Now this is where it gets more interesting. The functions a(); and b(); are assigned within foo()<br />
and can now be used outside of foo(). But what do these functions do? They manipulate a variable<br />
defined inside the function scope of the function foo() itself.<br />
This means that when we call a(); or b(); in the global scope, we are still working with the references<br />
to the variable x, which itself resides within the scope of the function foo().<br />
A good metaphor for this would be that a(); and b(); are sort of like tweezers that you use to<br />
reach inside the scope of foo(); from the global scope. These functions can manipulate memory<br />
(in this case the variable called x) defined inside foo().<br />
This functionality is amazingly useful to make our objects persist. Objects such as variables<br />
and functions can be stored within another “container” function such as foo(); in this example.<br />
But wait, isn’t foo() also an object, as we discussed earlier? It is. So you can see now, how objects<br />
can contain other objects inside them.<br />
This cascading property of objects is very important. Storing objects inside other objects is<br />
an incredibly useful concept used to design computer software in any language that supports<br />
objects (aka, Object-oriented programming languages.)<br />
JavaScript is not fully an Object-Oriented Programming (OOP) language, but it does support<br />
this “matryoshka”-like quality of objects, where they can be stored within one another. Without<br />
this principle, function closures would not make much sense.<br />
23
What Exactly is a JavaScript Variable?<br />
Learning isn’t always about explaining new complex subjects. Sometimes it’s about bringing to<br />
your attention the deeper details of the already known. In-depth understanding makes programming<br />
more interesting. It’s easy to think that you know everything about variables. But<br />
there are many details that often slip from the viewfinder of an untrained eye.<br />
While working on Revision Two of this book, I have added more chapters to the JavaScript<br />
Bootcamp to talk more about the basics of JavaScript programming. One of the subjects deals<br />
with JavaScript variables.<br />
One of the goals with my writing is to give a deeper insight into simple concepts. I believe<br />
that by reaching down to the very reason for why something works a certain way the reader is<br />
given an opportunity to become a better JavaScript programmer.<br />
When teaching a computer language such as JavaScript numerous tutorials talk about using<br />
variables in terms of showing how they work. But little is said about what they are. We are<br />
often told that we can define variables using the var keyword. But understanding what they are<br />
and where they come from gives us a deeper insight into JavaScript programming. In fact,<br />
many JavaScript concepts, such as objects, are much easier to understand if we can compare<br />
them with variables.<br />
Are They Variables or Objects?<br />
* * *<br />
Because everything in JavaScript is an object this sometimes creates confusion among the beginners<br />
who are seeking to understand JavaScript data types. If everything is an object, then<br />
what is a variable? And if a variable is indeed an object, then why are we using the keyword<br />
named var to define it? Wouldn’t something like obj be more appropriate?<br />
The answers to such questions are often determined by creators of the language specification<br />
itself. The fact that someone decided to create a specification does not guarante that this specification<br />
will be ideal. Regardless, when it comes to any data in any language, it is always tied to<br />
the same concept: all data is stored in computer memory on the microprocessor.<br />
Keep in mind that all variables are physically stored in computer memory at random addresses.<br />
When we access a variable, we access the part of computer memory it is stored in. A variable<br />
is stored at a unique and random memory address chosen by the operating system.<br />
We’ll get to how variables are physically stored in computer memory in just a moment.<br />
24
Even though it is possible to omit the var keyword from a variable definition, I recommend to<br />
always define your variable with the var keyword:<br />
var apples = 1;<br />
Let’s take a look at some of the basic principles behind variable definitions:<br />
1. A variable is often (but not always) a temporary storage of computer program data.<br />
2. Variables are used to store and manipulate data during program life cycle.<br />
3. The var keyword can be ommited from definition. But doing so is not recommended.<br />
4. The type of a JavaScript variable can be integer, string, boolean, function, array or JSON.<br />
5. In JavaScript a variable is also an object.<br />
6. The variable allocates enough physical computer memory to store the specified value.<br />
Variables are not unique to JavaScript. In other languages variables are created using all kinds<br />
of keywords. In PHP a variable name is prepended a dollar sign as in $apple. In C++, each<br />
different type of a variable has its own keyword. For example int for an integer type, char for<br />
a text character or short for “half ” a variable which is 2 bytes in length. 4 bytes would be a full<br />
32 bit set. On a 64-bit computer processor, an integer is 64-bit long.<br />
In JavaScript we use the var keyword to define a variable of any type. How does JavaScript<br />
determine the type of a variable being created? The type is defined by the assigned value. If we<br />
say that apples = 1, JavaScript automatically creates a variable of type integer.<br />
Determining Variable Type<br />
JavaScript variable definitions are typeless. This means that we can create any type of a variable<br />
and during the program lifecycle we can overwrite it by assigning a new value to it. This new<br />
value doesn’t have to be of the same type as the original. In comparison, this wouldn’t be true<br />
in languages like C++, where a variable of type integer can only be assigned an integer value.<br />
Typeless variables such as ones used by JavaScript can be reassigned, or turned into a different<br />
type using the equal sign. In C++ this process is known as type casting and requires manual<br />
action. But this is completely legal in JavaScript and happens automatically. To check the type<br />
of a variable at any point of its existence, we can use the typeof function:<br />
Parameter Returned result (as string)<br />
typeof(1) “number“<br />
typeof(“hello“) “string”<br />
typeof(true) “boolean”<br />
typeof(object) “object”<br />
typeof(null) “null”<br />
typeof(orange) “undefined” given that the variable named orange does not exist (was never defined)<br />
25
A variable allocates enough data storage in memory to store its value:<br />
Random Access Memory.<br />
RAM provides the computer program with<br />
memory reserved for variable definitions<br />
and other data storage. All JavaScript variables<br />
are stored in computer memory.<br />
RAM<br />
Variables are created and stored inside<br />
the computer processor.<br />
When a variable is defined, depending<br />
on the type of the computer processor, a<br />
number of bytes will be allocated to store<br />
the value specified by the programmer.<br />
In this case, enough memory to store the<br />
integer value 1 will be allocated.<br />
On a 32-bit processor, 32 bits of space<br />
will be allocated to store this number. In<br />
binary format, it looks like this:<br />
00000000 00000000 00000000 00000001<br />
The actual data is stored as 0s and 1s on the microchip. Even though in the example above the<br />
variable named apple equals 1, on a 32-bit processor a set of 32 0s is created. We’ll get to binary<br />
logic in a bit. For now just think of variables as values stored at a unique memory address.<br />
The truth is that even variables defined with the var keyword are objects. But because it is<br />
possible to start using variables to manipulate data by learning their simple syntax, many<br />
people never bother studying them with a greater degree of depth.<br />
It is fair to say that a variable itself is not an object. It is merely a name/handle to the object.<br />
An object is the data used in your program. Therefore, it makes sense that a variable can refer<br />
to different types of objects like strings, integers, functions, arrays and objects created using<br />
the JSON notation. We will continue discussing JavaScript objects later in the book.<br />
Variable Data Storage, Memory and Operators<br />
You are probably already familiar with JavaScript operators like the plus, minus and multiplication<br />
signs. They allow us to do common logical operations on integers and even strings. But<br />
as we just discussed above, the nature of a variable is in its physical representation in memory.<br />
In memory, a variable is not stored as a name as seen in a JavaScript program. The name apple<br />
exists only as an alias to the physical location in memory on the microchip. This value is represented<br />
as a long string of 0s and 1s on the microchip at a unuque memory address. Knowing<br />
this becomes incredibly important if we are to understand how bitwise operators work.<br />
26
We’ll get to the bitwise operators in a following section of the book.<br />
The actual value of a variable exists at a unique address in memory. The name apple is an alias<br />
to that address. For us humans it is easier to communicate in words and phrases than in numbers,<br />
like computers do. The name apple is a reference to a unique address that could look<br />
something like 0xFA074315 in hexadecimal (base 16) number system.<br />
In other words, var apple = 1, is the same thing as 0xFA074315 = 1. This hexadecimal address<br />
is chosen by the operating system at random, as our program executes. It is the RAM address.<br />
This makes sense now why this memory is called RAM, or Random Access Memory. It’s because<br />
variables and other computer program data is stored at a temporary random address.<br />
Let’s do a simple review to show how this relates to JavaScript code. Let’s assume that we have a<br />
variable var apple = 1. Let’s compare it to actual representation in computer memory:<br />
0xFA074315<br />
var apple = 1; is the same as 00000000 00000000 00000000 000000001<br />
Even though the stored value is 1, all those other zeros are still part of the same integer called<br />
apple. They are just not being used. This is because the minimum size of an integer on a 32-bit<br />
computer is 32 bits long. This is just how data is stored in computer memory. The 0s and 1s<br />
are actual physical switches on the microprocessor. Of course if you are on a computer with a<br />
64-bit processor, the integer would consist of 64 bits or 8 bytes. This gives us more processing<br />
power but that’s beyond the subject of this book.<br />
That’s a lot of 0s. To access or manipulate them, we can use the bitwise operators. But before<br />
we get to bitwise operators its essential to understand how binary numbers work.<br />
In order to understand binary numbers it’s a good idea to start with an example that explains<br />
what happens when we increment a value of a binary number by one unit. There is a certain<br />
pattern that forms. I broke down the proecss of incrementing a binary number into steps.<br />
Shortly, we will take a look at these steps in detail. However, before looking at these diagrams<br />
you should understand a few important things.<br />
Let’s increment the binary value 00000001 (which is 1 in decimal) by one unit.<br />
00000001 becomes 00000010<br />
This is 1 in decimal This is 2 in decimal<br />
1. Binary increment by one unit is done by shifting the leading bit to the left.<br />
2. As the leading bit continues to shift left, it starts to free up zeros to its right.<br />
27
Do you want to really understand programming? Or just write a few scripts and forget it?<br />
Binary logic is an incredibly important concept. It may seem complicated at first, but I assure<br />
you that by taking just 10 minutes to look at how binary logic works, a whole new world of<br />
possibilities will open up and you might start seeing things in a slightly different way.<br />
You and I have been using the decimal counting system from our birth. Decimal means base<br />
10. Perhaps counting up to 10 and starting over as in 11, 12, 13, 14, 15 and so forth came from<br />
the fact that human beings have 10 fingers. Whether that’s true or not, I don’t know. But if we<br />
look at it that way, then a computer processor only has 1 finger. And it can either raise it like a<br />
flag by showing that a bit is set to 1 or <strong>hide</strong> it by showing us nothing, or 0.<br />
How would you count if you only had one finger? That seems to be like the only way. But computers<br />
have memory that has enough space to store many values. So using this finger ballet<br />
the computer operates on large data sets even though it only has one finger to do it with. How<br />
does it then store values in memory? By using one finger to flip some values on and others off,<br />
across the entire memory board.<br />
Since we know that in a binary number a value can be only 0 or 1, then changing that value is<br />
always a toggle. If a value is 0, it can only be changed to 1. If a value is 1, it can only be changed<br />
to 0. We flip bits like they are lightbulb switches.<br />
The computer is all powerful. It can flip any bit of information at any time if you instruct it to<br />
do so. Which bits will you want to flip on or off? That’s entirely up to you. But when it comes<br />
to incrementing a binary number by one unit, there is a certain pattern that forms. Knowing<br />
this pattern will probably not make you a better JavaScript programmer. But it might give you<br />
a deeper insight into how computer work.<br />
* * *<br />
Human beings become fascinated about control. When I was 12 years old, my uncle showed<br />
me how to draw a line on a computer using the BASIC language. I can tell you that this event<br />
alone fascinated me so much (I could now draw lines on the screen of a computer!) that I saw<br />
myself making video games. It motivated me to continue exploring the world of computer programming.<br />
It let me know that I could control the screen by issuing commands. It was fun.<br />
The knowledge of binary numbers may not be necessary for most tasks associated with web<br />
development but knowing that this kind of thing goes on inside a computer can awaken the<br />
inspiration in someone. I hope, in the same way that my uncle awakened it in me.<br />
We have already discussed that to increment a binary number by one unit we shift 1 to its left,<br />
opening up more room for zeros to its right. But we have only discussed this process in the<br />
context of going from 1 to 2. How do we go from 2 to 3 in binary logic? Let’s take a look, because<br />
we don’t just keep shifting the leading 1 to the left in this case. Something else happens.<br />
28
Incrementing a Binary Number<br />
Step Dec. Binary Commentary<br />
A 0 00000000<br />
B 1 00000001<br />
C 1 00000001<br />
D 2 00000010<br />
E 3 00000011<br />
F 3 00000011<br />
G 4 00000100<br />
H 5 00000101<br />
I 6 00000110<br />
J 7 00000111<br />
K 8 00001000<br />
L 9 00001001<br />
M 10 00001010<br />
N 11 00001011<br />
O 12 00001100<br />
P 13 00001101<br />
Q 14 00001110<br />
R 15 00001111<br />
S 16 00010000<br />
We begin with a clean slate. This is 0 in binary and decimal.<br />
Start by switching the right-most bit to on position. Another<br />
way of thinking about it is that we shift 1 left into the number.<br />
To increment by 1, start by shifting this bit to the left.<br />
A zero to the right is now open. We just incremented the value<br />
by one. The equivalent of 00000010 in decimal is 2.<br />
Before we move on we first need to fill in remaining zeros to<br />
the right. Note that 3 isn’t 00000100. That’s a common mistake.<br />
We ran out of space. So, the next step is to move the leading 1<br />
to the left again, and zero out everything to the right.<br />
This is 4 in decimal.<br />
The process repeats itself.<br />
It looks like we exhausted all combinations. Just like in step G,<br />
we shift left and zero out again.<br />
11 is 1011 and not 1100 because we are always concerned with<br />
filling in the two right-most 0s first. See steps A-J. Same thing.<br />
Zero out.<br />
Shift left.<br />
Zero out.<br />
29
What is a Variable?<br />
Variables can be thought of and used in so many different ways that it would be pointless to<br />
give them one specific definition. In the context of a computer program, what variable is can<br />
only be understood by experimenting and writing your own computer programs.<br />
A variable consists of a name and value.<br />
var x; // Create a variable but skip the value.<br />
var x = 1; // Create a variable and assign the value of 1 to it.<br />
var a = b = c = 1; // Create three variables and assign value 1 to all of them.<br />
Everything in JavaScript is an object. Therefore, all variables we can possibly create are objects.<br />
An object is a concept. An idea. An object is not stored in computer memory with 0s and 1s.<br />
It can be thought by the programmers as a theoretical structure of the program. The computer<br />
processor only sees 0s and 1s. It doesn’t care about how we think. It just does what it’s told.<br />
This means that the concept of an object doesn’t exist anywhere in the computer itself. It exists<br />
only in our head. That is how humans think - in terms of objects. It’s a part of the creative process<br />
inherent to all of us. There are objects inside other objects. Like ideas inside other ideas.<br />
So what exactly is a JavaScript variable then? Let’s put it this way. If a computer program is a<br />
novel, then a variable is a word. A function is a sentence. And a block of code that calls a number<br />
of functions is a chapter.<br />
A variable is a versatile tool which can be many things. Theorethically, it is just a name that we<br />
create as an alias to a placeholder somewhere in computer memory at a random location. This<br />
way we don’t have to memorize the actual computer address just to refer to that location in<br />
memory every time we want to do something with that variables.<br />
Once we assign a value to a variable it becomes that value. If we assign an object to a variable<br />
name then that name becomes the object. If we assign a function, it becomes a function. The<br />
value of a variable is up to the context in which that variable is used.<br />
A variable can even refer to a an object created using the JSON. So as you see, the variable<br />
name is a reference to something. A variable is determined by its value. The name of the variable<br />
is a reference to that value.<br />
A variable can also be an integer or a string. But even a number or a string is an object in JavaScript.<br />
The value of the variable is always an object. This is why sometimes it is thought that<br />
variables are objects. But it doesn’t mean that the name of the variable is an object. The name is<br />
just a reference to the address in memory where that value is stored.<br />
30
Bitwise Operators<br />
With a solid understanding of binary numbers we can easily understand bitwise operators.<br />
Bitwise operators work on binary numbers. The difference between regular operators you<br />
may already be familiar with (like plus and minus which work with base-10 or decimal number<br />
system) is that bitwise operators let us manipulate individual bits of data within the variable<br />
value itself. Bitwise operators allow us to flip the state of an individual bit into on or off position<br />
in different ways.<br />
Bitwise operators & | ^ ~ > >>><br />
A good practical example of using bitwise operators would be storing user settings inside bits<br />
of an integer, instead of using the integer value itself. This is extremely helpful and a much versatile<br />
way of storing yes or no type of information. Let us remember from the previous section<br />
of the book that an integer is represented by 32 bits of information on a 32-bit computer. This<br />
means that one 32-bit integer has 32 spots that can be occupied by either 0s or 1s. These 0s and<br />
1s can be manipulated in various ways using different bitwise operators:<br />
& Bitwise AND operator<br />
| Bitwise OR operator<br />
^ Bitwise XOR operator<br />
~ Bitwise NOT operator<br />
> Bitwise Right Shift operator<br />
>>> Bitwise Zero-fill Right Shift operator<br />
Please note that leading zeros of a binary number can be skipped when refering to them in<br />
writing. This means that the binary number 00000100 (or 7 in decimal) can be also written as<br />
0100 or even 100. But 100 in decimal is one hundred. For this reason, when referring to number<br />
100 in binary it is often written as 100b to avoid confusion.<br />
In fact the Assembly Language (a language that talks in raw computer instructions directly to<br />
the microprocessor) programmers often see bytes as split into a lower and higher halves:<br />
0000 0001<br />
The higher half The lower half<br />
To make bitwise operations easier to understand the examples throughout the next pages will<br />
use only the lower half of the byte. In other words examples will be simplied to 4 bits.<br />
31
In order to understand bitwise logic, let’s pick two binary numbers to see what happens when<br />
we use bitwise operators on them. By refering to the table on the Incrementing a Binary Number<br />
page we can choose two arbitrary numbers. Let’s say Seven (0111) and Nine (1001). But<br />
because binary numbers are a little unique in terms of how we assign them to JavaScript variables,<br />
there is a small problem.<br />
In JavaScript there isn’t a way to literally define a binary number. In fact, trying to define a<br />
binary number using its literal representation as in example below we will be defining an octal<br />
(base 8) number instead. JavaScript simply doesn’t have a direct way to define a binary value.<br />
var apple = parseInt(111, 2);<br />
var apple = parseInt(“0111”, 2);<br />
Octal, not binary.<br />
var apple = 0111;<br />
var apple = 7;<br />
var apple = 0x7;<br />
Evaluated as the binary number 7. Note that 0111 would<br />
generate an error. Do not pass leading zeros to parseInt<br />
when specifying a binary number to avoid a syntax error.<br />
However, if we pass the binary number as a string, then<br />
we are allowed to use leading 0s with no problem.<br />
Value is an octal number equal the decimal 73, not 7.<br />
In JavaScript numbers starting with leading 0s indicate<br />
the octal system, not binary. Avoid making this mistake.<br />
The familiar decimal system.<br />
This is the hexadecimal format. 0x7 equals 7 in decimal.<br />
In the third example notice how the number looks as if it is in binary format. But it’s actually<br />
not. By default JavaScript processes a value that starts with a zero as an octal number (base 8)<br />
not binary (base 2), which is what we’re looking for.<br />
An octal number is represented by digits between 0 and 7. And cleverly enough, JavaScript understands<br />
all of this and determines the number type automatically by looking at its value. For<br />
example 0118 would be equal the decimal 118 even though it has a leading 0. This is because<br />
JavaScript knows that the digit 8 is not part of the octal system (0-7 only). But 0117 would be<br />
treated as an octal number and the result would equal the decimal 79. Try it yourself:<br />
var decimal = 0111; // will equal the decimal 73, not the binary 7, nor the decimal 111.<br />
var decimal = 0117; // will equal the decimal 79.<br />
var decimal = 0118; // will equal decimal 118.<br />
If this confuses you, you are not alone. This is just the way JavaScript deals with numbers.<br />
Without an explicit way to specify a number type, things will be confusing. This is why it’s<br />
important to stick to one base. In the end, all numbers are represented in binary format inside<br />
the computer. So the number system becomes our choice. In order to understand bitwise operator<br />
logic we need to use the binary system, yet, it’s not directly available.<br />
But that doesn’t create a big problem for us as long as we know what the number equivalents<br />
are in the binary format. Equipped with parseInt, we are ready to explore the logic behind<br />
bitwise operators.<br />
32
The only way to directly specify a number in binary format is by using the parseInt function.<br />
In particular we are interested in the second parameter radix. The radix argument gives us<br />
control over the numeric system of the variable. If we pass 2 as the radix, we will be telling<br />
parseInt to literally parse the value as a binary number, not as a decimal integer, an octal or<br />
hexadecimal number. Which is exactly what we need.<br />
The function parseInt converts the binary number into a decimal number.<br />
var decimal = parseInt(0111, 2);<br />
var decimal = parseInt(“00000111”, 2);<br />
var decimal = parseInt(111, 2);<br />
When the first argument is passed as an integer,<br />
this will generate a syntax error. No leading zeros<br />
are allowed.<br />
We can simply pass 111 as an integer. But a better,<br />
more explicit way to specify a binary number is to<br />
use a string.<br />
Returns 7, because 0111 in binary is 7 in decimal.<br />
You can do it this way, it’ll still work. But it’s not<br />
recommended.<br />
Note that in JavaScript bitwise operators do not work directly with binary numbers. The actual<br />
value of the variable specified as a binary number using parseInt will still be in decimal format<br />
if we output it with the alert() function.<br />
However, that is of little importance to us. The numeric system is only a shell. It is just a way<br />
for us to work with numbers. And no matter what numeric system we use when we work with<br />
numbers, in computer memory the data is always stored in the binary system. The decimal<br />
numbers we are using when we work with JavaScript variables have binary counterparts.<br />
Bitwise operators work on individual bits of two binary numbers. Bitwise operators work with<br />
any two binary values of the same length. But let’s keep things simple and consider two binary<br />
values represented by a single bit just to see how they work.<br />
Here is a quick example of the bitwise AND operator working on two bits: 1 & 0 = 0<br />
Let’s see what happens when we apply the bitwise AND operator represented by the & sign<br />
to two values. The rules of the bitwise AND operator state that the result will be equivalent to<br />
multiplying the two given values. For example, 1 & 0 = 0 because 1 × 0 = 0.<br />
Bitwise AND operator &<br />
Value 1 Operator Value 2 Result<br />
0 & 0 0<br />
1 & 0 0<br />
1 & 1 1<br />
33
At first this might seem confusing. Why would anyone want to perform some odd operations<br />
on single bits of a number? But remember, the binary number can act more like a switchboard<br />
with some values on and some off. One of the things we can do with a bitwise AND operator is<br />
to check if.<br />
Let’s now take a look at the bitwise OR operator. The rules of the bitwise OR operator state<br />
that as long as one of the values is 1, the result will always be 1. Only if both values are 0 the<br />
result will be 0 as well. If both values are 1, the result will be 1.<br />
Bitwise OR operator | Example<br />
Value 1 Operator Value 2 Result<br />
0<br />
1<br />
|<br />
|<br />
0<br />
0<br />
0<br />
1<br />
0101<br />
OR 0011<br />
----<br />
1 | 1 1<br />
= 0111<br />
JavaScript examples of the bitwise OR operator:<br />
var result = 5 | 3; // result is 7<br />
var result = 2 | 8; // result is 10<br />
To perform binary operators on decimal numbers makes little sense. But these operations can<br />
actually be meaningful if we start looking at them in terms of binary numbers. For example,<br />
the bitwise OR operator can be used to add bits to an existing value:<br />
0010 | 0001 = 0011<br />
and the bitwise AND operator can be used to ensure that a bit is off by &-ing a 0:<br />
0011 & 0001 = 0001<br />
You may never have to deal with binary numbers in your JavaScript program. However they<br />
may become useful for things like saving space when storing flags or user settings in a database.<br />
34
<strong>Understanding</strong> JSON Definition<br />
While writing new episodes for my <strong>jQuery</strong> Tutorial newsletter many people have asked me<br />
why some variables are defined using quotation marks and why others don’t.<br />
In particular with regard to the animate function example from the previous page, I was asked<br />
the question: Why are there quotation marks around the argument “linear” but not around the<br />
integer whose value is 1500?<br />
We have already talked about the fact that JavaScript function parameters are typeless. This<br />
means that you can pass any type of an argument to them. An argument can be a string (text<br />
enclosed using quotation marks) or an integer (simply a digit.) JavaScript functions parameters<br />
do not determine or ask for the obeject type passed to them like C++ functions do.<br />
The assumed type of the parameter is determined by the programmer, not by the language<br />
specification. This means that when constructing a function of your own you are responsible<br />
for determining the type of the arguments that presumably will be passed to that function.<br />
It’s your responsibility to write the function in such way that handles any possible type of a<br />
parameter passed to it. <strong>jQuery</strong> programmers made the decision that the first parameter of the<br />
function animate() should be a JSON, the second an integer, and the third a string.<br />
JSON is the syntax rule for defining an object in JavaScript. An object can contain a number of<br />
variables, functions or other objects. Let’s take a look at an incredibly basic example of JSON<br />
object definition:<br />
var obj = { a: 1, b: 2 };<br />
It’s important to note that neither var, nor obj are referred to as JSON. JSON is in itself only a<br />
guideline for object definition in JavaScript as seen between the two { and } brackets. One of<br />
the most important things about JSON is that it uses the : (colon symbol) and the , (comma) to<br />
define the inner contents of an object. In other words, that’s just the way the syntax was defined<br />
by the creators of JavaScript language specification (Originally known as EcmaScript.)<br />
JSON in itself is a unique data representation like var or function. Except it has no keyword<br />
definition. In other words { var a: 1, var b: 2 }; would be a wrong way to create an object and<br />
this would create a JavaScript syntax error. This is important because there is actually a second<br />
way of creating objects in JavaScript using the function keyword where defining a using<br />
var a = 1; would actually be legal, but we will discuss this in another section of this book.<br />
35
Let’s display the variable “a” currently stored inside the object we just created obj. To access a<br />
member variable of an object we use the . (dot operator) as in the following example:<br />
alert(obj.a);<br />
This will output “1” in an alert box because that’s the value of a as defined in the previous example.<br />
In the same way we can access any variable stored inside of an object that was created<br />
using the JSON notation. But what kind of other things can we store inside a JSON?<br />
The answer is simple. Because everything is an object in JavaScript, we can store pretty much<br />
anything inside JSON, even another JSON itself:<br />
var json = { json: { json: { x: 1; } } };<br />
And to access the x property in this scenario we could do the following:<br />
var x = json.json.json.x;<br />
36
Making HTTP Requests with Ajax<br />
What you will learn:<br />
Ajax and <strong>jQuery</strong><br />
Asynchronous HTML form submit example<br />
Extra material: Inserting Form Values into MySQL Database on Submit<br />
MySQL Database wrapper class<br />
Source code for “submit.php”<br />
Storing submitted form data into MySQL database using a PHP script<br />
When you talk about using Ajax with <strong>jQuery</strong>, you can either say little or you can say a lot. I’d<br />
like to think that the latter is a more generous choice for the readers of my newsletter! I like to<br />
go in detail.<br />
I’m not going to bore you with all the details and syntax of every single parameter you can<br />
possibly use. And in the spirit of my previous tutorials, I’d like to focus on practical usage of<br />
making Ajax calls.<br />
Let’s face it, most things you will do with Ajax are about making a GET or POST request and<br />
returning the result. The result is the data returned by whatever script file you have chosen to<br />
make a call to.<br />
This result is simply the text version of the outcome of executing that file. For example, if you<br />
have a PHP file that prints “Hello” and exits, then this “Hello” is what will appear in the result<br />
of your Ajax call.<br />
You can pass parameters to an Ajax call just as you would to a web page. An Ajax merely executes<br />
a script file, in the same exact way as you would if you typed the URL of that script<br />
directly into the address bar in your browser.<br />
First things first. Let me just put it out there that in order to make an Ajax call, <strong>jQuery</strong> has a<br />
special function that looks like this:<br />
$.ajax(“script.php”);<br />
Really, it’s that simple. But as you may know the devil is in detail. This will merely call the file<br />
script.php (note, it can be script.asp, data.txt, an image, XML file or any other file that your<br />
browser can open).<br />
37
What’s important is the return value. The example above ignores the return value completely.<br />
Luckily, <strong>jQuery</strong> allows us to capture it. In order for us to see this in action, we need to use a<br />
slightly different syntax shown below:<br />
$.ajax( { url: “script.php”,<br />
type: “post”,<br />
success: function(result) { alert(result); }<br />
});<br />
Still the same function. The only difference is that now we are using JSON with objects inside:<br />
url, type and success. JSON is discussed earlier in this book.<br />
Note that the “result” parameter passed to the success function is the data received from the<br />
script. You are the one to decide what that returned data should be within your “script.php”<br />
file. Again, it can be XML, plain text or any other kind of data, depending on the purpose of<br />
your asynchronous HTTP request. You can format the function above in any way you wish,<br />
but the point is that you specify either the POST or GET type using the “type” parameter.<br />
Remember that everything in Javascript is an object? This is what makes it possible to assign a<br />
function closure to the success parameter in the example above. Even “script.php” and “post”<br />
values are actually objects of type String.<br />
What are some of the things that Ajax can be used for?<br />
Forms: <strong>jQuery</strong> Ajax is incredibly helpful when dealing with HTML web forms. Using selectors<br />
it is possible to collect and send all values from all fields of the form directly to your form<br />
processing script without having to retype the id’s, names or values from the form elements.<br />
Let’s take a look at how you can use <strong>jQuery</strong> selectors along with Ajax to submit information<br />
from an arbitrary form. Let’s say we have a form like this:<br />
<br />
<br />
<br />
<br />
<br />
<br />
Note that there is no need to use the form tag at all unless you think you must. We’re avoiding<br />
the regular HTML form submit and overriding it with the way we want it to work.<br />
38
There is one curious thing about this code. What is this getform function? As you can see,<br />
this function returns the parameters we are passing to submit.php, but where does it get them<br />
from? It gets them directly from the input elements in our form. The second parameter is<br />
‘#form’ - it is the context. We already discussed context in my previous <strong>jQuery</strong> tutorial called<br />
How to speed up <strong>jQuery</strong> selectors. Head there to refresh your memory.<br />
The first parameter “input” lets us specify a <strong>jQuery</strong> selector. In this case, we only have input<br />
fields. But if we had textareas for example, I could also say:<br />
$.ajax({url:’submit.php’ + getform(‘textarea,input’, ‘#form’), type:’post’})<br />
Let’s take a look at the definition of getform function:<br />
function getform(element, parent)<br />
{<br />
var ret = “?”;<br />
var Length = $(element, parent).length;<br />
var idnamelist = new Array();<br />
var idvaluelist = new Array();<br />
for (var i = 0; i < Length; i++)<br />
{<br />
idnamelist[i] = $(element, parent)[i].id;<br />
idvaluelist[i] = $(element, parent)[i].value;<br />
ret += idnamelist[i] + ‘=’ + idvaluelist[i];<br />
if (i < Length - 1)<br />
ret += “&”;<br />
}<br />
return ret;<br />
}<br />
You can further simplify this function, but the point is that I broke it down into variables to<br />
make sure it’s easy to see what’s going on.<br />
The getform function goes through all elements of type specified in the first parameter. You<br />
can use just one element, for example “input” in this parameter, or you can add others. You<br />
just have to separate them by comma as in “input,textarea”. This will be passed on to the dollar<br />
sign function as a <strong>jQuery</strong> selector. The second argument “parent” is the context. We don’t want<br />
to look at all input fields on the page, only those within the DIV element with id = “form”.<br />
When the Submit button is clicked, <strong>jQuery</strong> fires an asynchronous ajax call to execute “script.<br />
php” file, effectively passing all id’s and values of every single input element in our form. You<br />
don’t have to do anything else. There is no more Javascript code to write, and it will work even<br />
if you add more input fields into this form, or even textareas. Just make sure they all reside<br />
within the DIV with the id = “form”. Also note that the submit.php (or submit.asp) file should<br />
include your custom code for processing the form on the server.<br />
39
Inserting Form Values into MySQL Database on Submit<br />
The form example wouldn’t be complete without us knowing how to insert this form data into<br />
the MySQL database.<br />
In the previous part of this tutorial, using <strong>jQuery</strong> we were able to effectively collect all input<br />
IDs and VALUEs associated with those IDs, and put them into a neat submit script.<br />
No matter what input elements you place into this form, they will be automatically passed to<br />
the submit.php script, thank goodness for the getform(selector, context) function. You can add<br />
new input elements or delete existing ones. It will still work as long as each input element is assign<br />
an ID attribute with a unique name.<br />
But how do we insert this data into a MySQL database? Well, that’s the responsibility of our<br />
submit.php script. This is the script that is being called by our <strong>jQuery</strong> ajax function.<br />
But before we look at submit, I’d like to intoduce a PHP helper class containing several database-manipulation<br />
functions that will allow us to do basic things with MySQL database. Let’s<br />
take a look at what’s inside:<br />
Link to PHP library file in text format on my website:<br />
http://www.learnjquery.org/book/sourcecode/class.MysqlDatabase.txt<br />
(Download and rename to class.MysqlDatabse.php)<br />
Usage explained on the next page.<br />
Place this code into a separate file, say class.Database.php and put it in a convenient place on<br />
your server, in a folder called “php” or something similar.<br />
The above class uses a utility function called array_to_list. This function takes two parameters,<br />
the array of data (usually of type string because it contains names of table columns like<br />
first_name, last_name, email_address, etc.) and the second parameter is the quote character<br />
you want to use in the resulting string.<br />
The result value is a string of names separated by a comma. Each name is wrapped with whatever<br />
quote you specify as second parameter. The default is the ` quote, not ‘ or “. I find that this<br />
is the best quote character to use in MySQL queries for wrapping a column name in. Of course<br />
you can use ‘ or “ by overriding the second parameter of this function, but it’s up to you.<br />
Note that to use class.MysqlDatabase.php you must include it in your php file. In addition,<br />
you must provide your own database ip address, username, password and database catalog<br />
name throughout the file. Of course, prior to doing so you must first create a new MySQL database<br />
on your server or run it locally using a local Apache installation.<br />
40
Now let’s take a look at the array_to_list function:<br />
// Convert values of an array to a list “quoted” by the character specified as the second $quote parameter.<br />
// This function allows us to convert arrays of data (of type string) into MySQL query parameters<br />
// This way we can pass an array rather than typing them out ourselves and typing quotes around them.<br />
function array_to_list($ar, $quote = ”`”)<br />
{<br />
$l = “”;<br />
if (is_array($ar))<br />
{<br />
$ac = count($ar);<br />
}<br />
if ($ac>0)<br />
{<br />
for ($i=0; $i < $ac; $i++)<br />
{<br />
$l .= $quote.$ar[$i];<br />
}<br />
}<br />
return $l;<br />
}<br />
return false;<br />
if ($i + 1 < $ac)<br />
$l .= “$quote,”;<br />
else<br />
$l .= “$quote”;<br />
Put this function into a file and name it “utility.php”, or whatever you think is best.<br />
Now... Let’s look at submit.php, which will conveniently include our utility function array_to_<br />
list, used by our database manipulation class:<br />
foreach($_POST as $k => $v)<br />
{<br />
$names[count($names)] = $k;<br />
$vals[count($vals)] = addslashes($v);<br />
}<br />
$Connection = new MysqlDatabase(); // connect to the database<br />
if (isset($Connection) && $Connection->isReady())<br />
{<br />
MysqlDatabase::insertTableData(“myform”, $names, $values);<br />
}<br />
41
I like code that you can “read” by just reading through it. Like a poem. It just makes sense.<br />
Notice a peculiarity in the foreach loop when I am enumerating the $_POST array we just<br />
received from our ajax call. Why am I using count($names) and count ($values) as an index to<br />
insert the value to instead of counting things using something like $++ or a similar indexing<br />
variable?<br />
Well, the count function will return 0 for arrays that don’t exist. Once we add one entry, it will<br />
return 1, then 2... and so on. The size of the array always points to its “next” placeholder available<br />
to us. So there isn’t a need to use an $index variable at all. Moreover, this makes code look<br />
less cluttered and more elegant.<br />
I have to also use the addslahes function, because we will be wrapping our resulting strings in<br />
our own quotes. This, however, depends on your database configuration. You will either have<br />
to add “magic quotes” or leave the input raw. You’ll have to look into your database config files<br />
on the host server.<br />
Ajax: In Conclusion<br />
Submitting forms is not the only use of Ajax, but in combination with PHP and MySQL it can<br />
be a powerful tool for making your form submitting easy.<br />
In the future I’m likely to add even more practical examples of using ajax here. Who said that<br />
we have to stop here?<br />
Web development is all about combinations of different languages, platforms and technologies.<br />
That’s why it’s difficult to talk about one without mentioning the others... and be complete.<br />
I hope that this code can be re-used by others, or at least it could give you an idea of how combinations<br />
of different languages can effectively make your scripts really great. Don’t stop here<br />
at just learning Ajax and <strong>jQuery</strong>, pursue studying other computer languages as well.<br />
42
Javascript as a Prototype-based Language<br />
JavaScript is a prototype-based programming language. In order to help us understand what<br />
this means, we can compare JavaScript with different kind of a language. Let’s take a look at<br />
languages such as Java and C++. These two are often referred to as Object-oriented languages.<br />
One of the fundamental ideas behind these languages is the concept of a class which is like a<br />
blueprint for creating an object.<br />
What is a class? Let’s start simple. In JavaScript we have the keyword var which is used to<br />
define a variable. We can later use this variable in our program to add numbers or concatenate<br />
strings.<br />
But what does a class define? By itself the keyword class defines a type of something. Literally,<br />
it can be a type of anything. This is only limited by your imagination and the purpose of your<br />
program. A class is an abstract concept, like a paintbrush. You choose the colors to paint your<br />
program with.<br />
The keyword class does not exist in JavaScript. But we need to talk about this keyword, and the<br />
concept of classes as a computer science subject, only to compare it with JavaScript in order to<br />
get a better insight on its prototype-based nature.<br />
But there is still a link between classes and JavaScript. That link is the concept of an object. The<br />
two languages C++ and Java use objects. So does JavaScript. And in a way a class is an object.<br />
And we will see how in just a moment.<br />
You may already understand what classes and objects are. But in order to gain a deeper understanding<br />
of JavaScript as a prototype-based language we need to briefly discuss them in the<br />
following section.<br />
Classes and Objects<br />
A class can be thought of as a creative logic tool that defines one of the many elements of your<br />
computer program. A class is a type of something. It is a blueprint that defines the construction<br />
and function a specific object that will be built from that class.<br />
Multiple classes can and often are designed to work with each other. That’s the point. You can<br />
create a class and call it class car. You can then create a class engine and use it to define an<br />
engine for the car. You can create different types of cars by adding different kinds of engines<br />
to them. In computer science this is referred to as object composition. Object composition is<br />
a method rarely used in JavaScript programs because the prototype method, which we will<br />
discuss in a moment, replaces it.<br />
43
An object is created from a class. And in JavaScript everything is an object by definition. This<br />
is why we never need to use the class keyword in the first place. Everything is already an object.<br />
Whereas in PHP, C++ or Java, this is not true. Conceptually, variables are data types and<br />
not necessarily classes in these languages. There is a clear distinction between variables and<br />
classes in those languages. But not in JavaScript which treats every single data type as an object<br />
by default. This is very important concept to understand and it is part of what makes JavaScript<br />
a prototype-based language. In an object-oriented language the entire program is a collection<br />
of these objects working together.<br />
An object is an initialized class. It is the physical representation of the class in computer memory,<br />
that is ready to be used by your program. While the class is merely a blueprint model, a<br />
design - the object of that class is the constructed result.<br />
The behavior and properties of an object can be defined during the process of object creation,<br />
also known as instantiation of an object. In other words, a new instance of an object is created,<br />
or initialized, from a specific model which is determined by its class.<br />
An object can also be modified by your program during the course of its existence until it is<br />
destroyed or in other words, erased from computer memory.<br />
Classes are the models for spawning new instances of objects. Using one class, you can spawn<br />
any number of different types of cars with different types of engines, transmission systems<br />
or tires. The number of objects that can be created is only limited by memory capacity of the<br />
computer on which your program is running.<br />
An Example of Object Composition. Object-oriented programming languages follow the<br />
same idea as in the real world, where real-life objects are constructed from a number of smaller<br />
objects. A car has an engine and wheels. A light bulb has a glass shape and socket base type.<br />
44
Let’s take a look at an example of an object in the C++ programming language. A class to represent<br />
bulb shape. And a class to represent the socket type.<br />
class Shape<br />
{<br />
int shape; // a digit<br />
};<br />
class SocketType<br />
{<br />
char type[32]; // a string<br />
};<br />
Let’s now take a look at how object composition can be used to define the light bulb class itself.<br />
class LightBulb<br />
{<br />
Shape shape; // The Shape object is included in this object’s composition<br />
SocketType socket_type; // SocketType is another object included in this one<br />
int state; // 0 - for off, and 1 - for on<br />
void turn_on(); // set state to 1<br />
void turn_off(); // set state to 0<br />
};<br />
It’s important to understand that this is C++. In JavaScript all variables are typeless, in other<br />
words when we define a JavaScript variable its type is determined by the value assigned to it.<br />
In C++ the type of a variable is determined explicitly by the programmer.<br />
In C++ we can define a class to be composed of previously defined classes of different types.<br />
Together they form a model for an object to be created from this class. As you can see object<br />
composition is an incredibly flexible computer programming paradigm.<br />
The programmer’s creativity is used to determine the composition of every single entity required<br />
by the program. You determine the design. In addition objects can have methods. In<br />
this example it’s turn_on and turn_off which would toggle the state between 0 and 1.<br />
Let’s not go into details of how to create classes in C++ and what int or void mean. After all<br />
this is a JavaScript book. What’s important is that this is one way of object composition. For<br />
now, take a note that this is the static way of creating objects. We’ll take a look at how Javascript<br />
does this in a moment.<br />
Two classes Shape and SocketType are used to construct one complete class LightBulb. This<br />
is called object composition. We still can, and probably even should use object composition as<br />
an effective method for object creation even in JavaScript - we will just have to think about in a<br />
slightly different way. In a prototype-based way.<br />
45
Dynamic Prototype-based Objects in JavaScript.<br />
The notion of an object in computer programming is such an important concept, that it actually<br />
relates to the design of the programming language as a whole. The period of time when<br />
the program begins and continues its execution is often referred to as the run-time or the program<br />
life cycle. And the way in which objects are designed in different programming language<br />
paradigms has a lot to do with this life cycle.<br />
Recall the C++ LightBulb class from the section above. In C++ these classes are entirely static.<br />
They cannot be modified during run-time. In C++, before you can run the program it must be<br />
compiled into an executable file first. Once the program begins execution, the classes are no<br />
longer allowed to be changed. This is not true in JavaScript. In JavaScript, objects can continue<br />
being modified during the program execution at run-time. Knowing this, we are getting<br />
closer to understanding prototype-based object composition.<br />
JavaScript programs compile within the browser itself (this is called “just in time,” JIT compiling<br />
but also known as dynamic translation in computer science) so we never have to worry<br />
about doing it manually like we would when writing a C++ program.<br />
* * *<br />
As we get deeper into exploring the concept of objects we will need to know about the tools<br />
given to us for working with objects. In terms of the mindset required when writing objectbased<br />
JavaScript programs, an object can be thought of as a toolbox, as a private space for<br />
making something very specific work a certain way. An object isolates specific functionality,<br />
making it easy to look at the entire program from the perspective of its design.<br />
On the next page let’s explore an important concept called the this object. It’s used by objects<br />
to refer to themselves from within themselves.<br />
46
The this Object<br />
Before I show you an example of a JavaScript object, I’d like to temporarily shift your attention<br />
to a concept known as the this object. The “this” object is a reference to itself. Every object has<br />
a reference to itself named this. You can think of the this reference as a variable that points to a<br />
location of an object in computer memory.<br />
But why in the world would we need to have a handle to an address in memory? Couldn’t we<br />
just create an object and use its name? This is true. But what if the object itself needed to use<br />
itself from within the functions within its own scope? What name would it use? It would use<br />
the this reference to itself.<br />
From within itself, LightBulb<br />
will use the this object, to refer to itself<br />
from within its own functions.<br />
this is a reference to the object itself,<br />
looking at itself from within itself.<br />
But from the scope of the JavaScript program<br />
we naturally use the class name<br />
LightBulb to refer to that object.<br />
One other way to think about it, is that while others refer to you by your name, you<br />
refer to yourself as I, I am, me, etc.<br />
The this object is a reserved keyword in JavaScript. In other words, you cannot give your variables<br />
the literal name this. That would create an error. It’s a reserved keyword to be used only<br />
as a self-reference of an object used only by the object itself.<br />
The this object is also present in C++ and Java. But what does it mean to be a self-reference? In<br />
order to understand this, we must think in terms of object composition again. When we create<br />
objects we can place other objects (variables and functions) inside them to create one complete<br />
object.<br />
47
Without knowing anything at all about objects the this keyword may be slightly confusing to<br />
understand in terms of how it is used in practice. So let’s now go back to our discussion of objects<br />
in JavaScript knowing that the this is a reference to itself.<br />
Just like in Java or C++, in JavaScript, it is also possible to add objects to other objects to create<br />
greater, more versatile constructs. In fact, the idea is exactly the same. In JavaScript there are<br />
two ways to create an object. One is by using JSON and another by using the function keyword.<br />
We will take a look at both, one at a time<br />
Creating a JavaScript Object Using JSON<br />
Let’s take a look at one popular way of defining a JavaScript object:<br />
var Object = { property: 1 };<br />
What we are seeing here is called JSON or JavaScript Object Notation. JSON begins with a<br />
curly bracket. We enter a property name, end it with a : (colon) and enter the value. Close it<br />
with a }; Notice the semicolon at the end.<br />
It’s possible to add more properties to the same object by separating them by comma:<br />
var Object = { property: 1, another: 2 };<br />
The code won’t compile if you add a semicolon after the last value (2). So we leave it blank.<br />
Writing it out on one line is very convenient for simple objects. But when we have more than<br />
one property we can format the object in the following way. Also it helps to memorize these<br />
precautions:<br />
var Object =<br />
{<br />
property: 1,<br />
another: 2,<br />
};<br />
Leaving a comma at the end is legal<br />
var Object =<br />
{<br />
property: 1,<br />
another: 2;<br />
};<br />
Adding a semicolon here will generate an error<br />
To access values of the properties property and another stored inside the main Object we will<br />
use the dot operator:<br />
var prop1 = Object.property; // prop1 will store 1<br />
var prop2 = Object.another; // prop2 will store 2<br />
48
Let’s rewrite the same LightBulb object from the C++ example above but using JavaScript and<br />
what we know of JSON this time:<br />
var LightBulb =<br />
{<br />
shape: 0,<br />
socket_type: “European”,<br />
state: 0,<br />
turn_on: function() { alert(“Lightbulb with “ + this.socket_type + “ socket is on.”); },<br />
turn_off: function() { alert(“Lightbulb with “ + this.socket_type + “ socket is off.”); }<br />
};<br />
All of the above: shape, socket_type, state, turn_on and turn_off are nothing more than objects<br />
stored within the main object called LightBulb. Within an object shape, socket_type and<br />
state are variables and referred to as object properties. But turn_on and turn_off are functions<br />
and within an object functions are referred to as object methods.<br />
Let’s access properties and methods from within this object using the . (dot) operator.<br />
// And a few examples of using this object:<br />
LightBulb.shape = 1;<br />
LightBulb.socket_type = “Mogul”;<br />
LightBulb.turn_on(); // This will display an alert message “Lightbulb with Mogul socket is on.”<br />
LightBulb.turn_off(); // This will display an alert message “Lightbulb with Mogul socket is off.”<br />
A few things are happening here.<br />
The keyword var can be used to create variables as well as objects. As mentioned earlier, everything<br />
in JavaScript is an object. Even variables defined using the var keyword itself. We then<br />
simply name our object LightBulb like we would any other variable and use the equal sign<br />
followed by a scope { ... }; and a semi colon, where the three dots determine the contents of the<br />
object we are creating.<br />
Notice that the definition of the “class” LightBulb which is done using the var keyword is also<br />
the instantiation. In other words, we are defining and initializing the unique, working instance<br />
of the object at the same time. This would be illegal in C++ and Java where definition<br />
and instantiation are done separately.<br />
In comparison, in languages like C++ and Java we must define the class first and only then<br />
initialize the object. In other words we create a unique working instance of that object whose<br />
definition cannot change during runtime of the program. In those languages, once an object is<br />
initialized we cannot modify its blueprint - the class definition itself. But in JavaScript, we can.<br />
49
More About JSON<br />
JSON is a data interchange format. Although it is influenced by the JavaScript syntax it is used<br />
in many other languages to represent data. It is not unique to JavaScript. In fact, it is often used<br />
to send already created objects over network to a program written in another language (such<br />
as Java) as string. Once Java receives that string it can then recreate a Java object using the<br />
JSON string that was received from an application written in another language.<br />
To create an object in JavaScript, we can use the JSON which stands for JavaScript Object Notation.<br />
It’s nothing more than the syntax you are seeing below:<br />
var main_object = { object1name: objectvalue, object2name: objectvalue };<br />
You can have more than one object name and value pairs separated by comma. The variable<br />
main_object is an object itself, whose parameters are specified using the JSON notation.<br />
Remember that everything in JavaScript is an object. This means that the objects object1name<br />
and object2name can be variables or functions. In other words, JSON is not limited to basic<br />
data types.<br />
The actual value specified in objectvalue can be any variable like an integer or a string. But it<br />
can also be an array, a function or even another JSON. Again, this is because everything in<br />
JavaScript is an object and the parameters inside a JSON are objects.<br />
As an example let’s take a look at a practical example of acceptable values in a JSON.<br />
var json =<br />
{<br />
animal: “cat”,<br />
legs: 4,<br />
eat: function() { /*eat*/ },<br />
array: [0,1,2,3,4],<br />
json: {<br />
primary: 1,<br />
secondary: 2,<br />
another_array: [“a”, “b”, “c”]<br />
},<br />
final: 7<br />
};<br />
alert(json.json.another_array[1]); //display “b”<br />
50
In order to access a value of an object from within the program we use the . (dot) operator. As<br />
in the following example:<br />
var light_bulb = { shape: 1, socket_type: “European”, state: 0 };<br />
light_bulb.shape = 2; // change bulb shape<br />
light_bulb.socket_type = “Mogul”; // change socket type<br />
light_bulb.state = 1; // turn on<br />
Everything in JavaScript is an Object<br />
Knowing a few things about classes and objects, let’s go back to the original question that<br />
started this section. JavaScript does not have the keyword called class. But it does have objects.<br />
How can that be? This is because everything in JavaScript is an object. All variables and functions<br />
are objects. Arrays and strings are objects of type Array and String, respectively.<br />
It would be difficult to determine what prototype-based language really means using only one<br />
sentence. But it’s easier now that we know something about the nature of objects in general.<br />
In order to understand what prototype means with a slightly greater insight, let’s consider the<br />
following points:<br />
Compile Time and Run Time<br />
Run time, or run-time is the period of time during which the program takes place. In other<br />
words, a period of time during which it executes or runs its course.<br />
We know that object-oriented programming languages make it possible to create an entirely<br />
independent object that shares the design model of the original class it was created from. This<br />
process happens during the run-time in computer memory while the program is being executed.<br />
Before executing the program, and before it begins to run, the objects are defined by the programmer.<br />
Objects are defined at the time the program is being written. The program is then<br />
physically executed by the computer at run-time.<br />
In purely object-oriented languages there is a concept called class inheritance. It implies that<br />
classes can be spawned as copies of other classes. It means that if you have a car with a particular<br />
type of an engine, you can quickly make a copy of that car using its original class. Class inheritance<br />
is a process that happens during the planning stage of your computer program and<br />
not during run-time. In other words, we define which classes will be inherited from which,<br />
before executing the program.<br />
51
In some programming languages the term compile time is used to describe the process of<br />
rewriting your code into machine code, one that the computer processor understands. For it<br />
does not understand JavaScript, C++ or PHP syntax. The processor only understands 0s and<br />
1s.<br />
Languages like C++ and Java require the program to be compile into machine code before executing<br />
it. The process of compiling a program in those languages is usually manual. In other<br />
words, the programmer needs to press the “compile” button on the Graphics User Interface<br />
withing the IDE (Integrated Development Environment) or start the compile process using the<br />
command line.<br />
Prototype<br />
In JavaScript the program is compiled by the browser just in time for being executed. In JavaScript<br />
this process is automated by the browser. It’s known as JIT or Just In Time compilation.<br />
It doesn’t mean it isn’t there just because we are never aware of it. All of your JavaScript programs<br />
are always compiled before they are executed. We never notice any slow-downs because<br />
most JavaScript programs are very short and are quick to compile. The reason for mentioning<br />
any of this at all is that this has a lot to do with the prototype-based nature of JavaScript. We<br />
will see how, in a moment.<br />
I won’t say it is because languages like Java are compiled that they are not prototype-based.<br />
Similarly, just because JavaScript has a JIT mechanism, it doesn’t mean that this is the only<br />
reason it is prototype-based. The subject of computer language design is more complex than<br />
this. And even in order to execute a Java program there is a JIT mechanism of its own running<br />
on the client machine.<br />
Where are we going with all of this as far as JavaScript concerned? The manual program compilation<br />
process is true mostly of C++, Java and many other languages. But in JavaScript, we<br />
can:<br />
re-define the composition of an object dynamically during run-time.<br />
This is the “prototype” part.<br />
The prototype is an “object prototype” that can be changed during execution of the program.<br />
In JavaScript objects are not derived from classes. In other words, even though class inheritance<br />
can be imitated in JavaScript, it is not the primary part of JavaScript’s design as a programming<br />
language. We use the dynamic nature of prototype-based object composition. All in<br />
real time during execution.<br />
52
Learning JavaScript Object Definitions<br />
When I was learning to write programs for the PC back in late 1990s, I have chosen C++ as my<br />
first programming language. Back then, you had to understand things like the command line<br />
and knowing what IDE (Integrated Development Environment) to use. In other words, you<br />
couldn’t just type up some code into Notepad and expect Windows to execute your program.<br />
The code had to be first compiled and only then executed. This is still how compiled languages<br />
like C++ work today.<br />
But HTML and JavaScript are much more accessible. In fact, their popularity among web programmers<br />
can be accredited to how easy it is to get started with them. The browser does the<br />
compiling and execution of your program. You just write the code.<br />
In order to run a C++ application on a Windows computer, the program has to be first compiled,<br />
built into an executable file that the Operating System understands and then launched<br />
by executing the file. The browser such as Internet Explorer, Firefox and Chrome are all examples<br />
of a desktop application that was compiled and built into an executable file first. When<br />
you click on its icon to launch the browser, you are executing the file that has been built by<br />
developers of the browser.<br />
But JavaScript and HTML code run directly inside the browser. There is nothing to compile or<br />
build. The program executes after it is processed (compiled and built into machine code) by<br />
the browser. This makes it incredibly easy for anyone to start writing JavaScript code. But that<br />
can be dangerous.<br />
Very often people jump into memorizing what a line of code looks like from online tutorials<br />
and books and then try to recreate it in their own programs with different parameters. But this<br />
approach to learning a language leads to confusion in the long run because of the lack of understanding<br />
internal mechanics of a language.<br />
Even though the process of writing the code was made easy by the automatic JIT (Just In<br />
Time) compilation right inside the browser, the problem still arises when it comes to learning<br />
53
JavaScript from scratch. If you are an absolute beginner, there are things you may not want to<br />
do. The understanding how to learn a programming language becomes important.<br />
The right way of thinking about JavaScript programming lies in understanding the creation<br />
and manipulation of computer data. In other words, variables, functions, integers, strings,<br />
arrays, etc. are the blocks of data we will define. This data will be manipulated by JavaScript<br />
statements and logical constructs we create during the period of time our program executes, in<br />
other words the run-time.<br />
One of these often overlooked concepts is the definition of objects in JavaScript. I have not<br />
seen many tutorials that actually spend time explaining this. They simply jump directly to<br />
practical examples. But in order to really get a grasp on the art of programming websites, we<br />
need to understand data creation and manipulation at the very root. We must thoroughly<br />
understand what’s going on at the very core of computer language syntax. And at the core of<br />
JavaScript there are objects and object definitions.<br />
Let’s take a look at an object definition from one of my previous tutorials, the LightBulb object:<br />
var LightBulb =<br />
{<br />
shape: 0,<br />
socket_type: “European”,<br />
state: 0,<br />
turn_on: function() { /* code that turns bulb on here */ },<br />
turn_off: function() { /* code that turns bulb off here */ }<br />
};<br />
Notice how we still use the var keyword to define an object, not a variable. This can actually<br />
be thought of as a flaw in the language design as it surely can confuse us. Is it a variable, or is it<br />
an object? Let’s analyze this structure in a slightly different way. Thinking of code using visual<br />
imagination, we can draw this diagram:<br />
54
This can be thought of as a mental model of this construct as seen from a beginner developer’s<br />
point of view. But with a little abstraction, it is possible to see even more.<br />
As I point out throughout this book everything in JavaScript is an object. This means, all variables,<br />
integers, strings, arrays, functions, anonymous functions, all arguments passed to all<br />
functions, all results returned from functions are objects. So the diagram above can be, once<br />
again, simplified as:<br />
This is the correct way to think about all objects. Even these branches of objects may contain<br />
more objects within them. And that can create an infinite chain of objects. Which isn’t impossible.<br />
Instead of saying that we are defining a variable using the var keyword it’s best to get used to<br />
thinking of the data being created in terms of an object. Because that’s what it is. As you can<br />
see, this gives us an abstract model to think about writing code that is much clearer.<br />
Are Variables Objects?<br />
Yes, they are. Even simple definitions such as var text = “hello”; will create an object of type<br />
String. It’s just JavaScript conceals this from us. Theoretically, we should think of everything in<br />
JavaScript as an object.<br />
It is still perfectly safe to think of data created using the var keyword as variables. And sometimes<br />
it is not required to think of them as objects. For example when we do something like:<br />
var a = 1 + 1;<br />
But that’s the simple stuff. If you want to understand how <strong>jQuery</strong> really works, and why it<br />
works the way it does, you will need to think of these things in terms of objects.<br />
Objects by definition are of recursive nature. This means that objects could contain other<br />
objects within them. Objects within other objects are accessed using the object method and<br />
55
property access operator - the . (dot) operator.<br />
For example, the object of type String (the variable whose value is set to”European” in the first<br />
diagram above is an object of type String. It’s not just a variable, it actually contains within it<br />
methods (functions) and properties (variables) that can be used right away without us having<br />
to define them.<br />
JavaScript’s String object already contains functions defined within it so that we are ready to<br />
start using them. For example, let’s access the LightBulb’s String object’s length property. We<br />
can do so using the dot operator:<br />
var len = LightBulb.socket_type.length;<br />
Notice that the dot operator is used twice. First after LightBulb to access its methods or properties<br />
and then after socket_type. The length property itself is an object of type Integer. How<br />
can we know for sure? Javascript has a special function called typeof that we can use to determine<br />
the type of an object by simply passing its reference as the parameter. Let’s use the good<br />
old alert function in combination with typeof to display the actual type of an object we’re dealing<br />
with:<br />
As you can see typedef will tell us the type of the object being passed to it. One little note to<br />
make is that the Integer object that is referred to as “number” is returned as the same type also<br />
for floating point numbers such as 1.572. In other words there is no distinction between an<br />
integer and a floating point number. They are both defined as an object of type “number” in<br />
JavaScript.<br />
56
Using typeof in a Real-World Scenario<br />
One interesting aspect of looking at everything as an object in JavaScript has to do with creating<br />
custom functions. This is something I mention in my jquery tutorial book all the time.<br />
Let’s say we want to write a function. Then, based on the type of an object passed to this function<br />
as an argument we want to do something different. The typeof function to the rescue:<br />
function func(value)<br />
{<br />
if (typeof(value) == “string”)<br />
{<br />
// it’s a string, process the string...<br />
}<br />
if (typeof(value) == “object”)<br />
{<br />
// it’s an object...<br />
}<br />
}<br />
But who would want to do it this way and why? The idea is actually utilized by <strong>jQuery</strong> object.<br />
Which is the same as the dollar sign $ object. Let’s take a look at the following <strong>jQuery</strong> code:<br />
Both functions do exactly the same thing - they select all div elements on the page located<br />
within the body element (which means all of them) and <strong>hide</strong> them. As you may know the second<br />
parameter of the <strong>jQuery</strong> object function we are seeing here is called context.<br />
The context parameter is nothing more than the target element within which we will search for<br />
any “div” elements. I chose “body” which is the main HTML container of the entire web page.<br />
We could have chosen any other element - that’s up to your site’s DOM structure. But that’s not<br />
the point of this example. The difference is in the parameter type passed to the function. What<br />
happens when a string is passed? What happens when an object is passed?<br />
The $(“body”) statement itself returns the object that contains the DOM that includes all elements<br />
within the “body” element.<br />
57
Why does <strong>jQuery</strong> do exactly the same thing even though the second parameter passed in two<br />
different ways? The typeof function to the rescue. The <strong>jQuery</strong> function written in such a way<br />
that it first determines the type of the object being passed to it as a parameter.<br />
If the context parameter is a string like “body” it will take its literal meaning and find that<br />
element using the text in the string. If the parameter is passed as an object (remember that<br />
$(“body”) is a function that actually returns an object) then the work is already done - we already<br />
have the object here.<br />
Internally, the $ function will skip the seeking algorithm (since the object already contains all<br />
the data.) This doesn’t mean that it’s faster, $(“body”) will still take time to obtain the object<br />
itself, it’s just that it’s done before this object is passed to the main <strong>jQuery</strong> function for processing.<br />
58
<strong>jQuery</strong><br />
59
Learning <strong>jQuery</strong><br />
The greatest thing about not knowing where to start is that you can start anywhere.<br />
Many web publications assume that the reader is already familiar with the basics. This process<br />
of skipping the basics makes it easy to exclude important principles of web development.<br />
I recommend creating some kind of a Web Application Template. This would be the starting<br />
point of a new website project. It’s simply a way of linking CSS and JavaScript files into one<br />
HTML file, the main application file of your web application.<br />
Modern web development may require understanding of several programming languages,<br />
frameworks and programming techniques. Just knowing <strong>jQuery</strong> is not enough.<br />
In order to really understand <strong>jQuery</strong>, we must also understand the environment in which it<br />
works. In other words, the structure of a web page. How are the components of a web application<br />
written in HTML linked together? How should they be linked together?<br />
This interconnectedness of different languages is a crucial concept we need to understand<br />
when developing dynamic web applications. This concept will be further explored.<br />
Knowing how to use CSS selectors is also a big part of understanding <strong>jQuery</strong>. Most of the time<br />
you will be selecting HTML elements, following specific selection patterns that you pass to the<br />
main <strong>jQuery</strong> object, which is often referred to as the dollar sign ($).<br />
CSS selectors play a big role in developing dynamic web pages in general. They operate using<br />
the same principles that regular CSS files do. If you have styled an HTML page with CSS<br />
before you may already be familiar with some of them. One such selector is the dot (.) operator<br />
- it selects element(s) of a class. Another is the number sign (#) operator - used to select an<br />
HTML element with a unique id.<br />
Furthermore, things that are trivial to an experienced developer may not be as easy to understand<br />
for those who have just begun their journey. For this reason, I decided to include this<br />
section explaining how everything in a webpage fits together.<br />
If you are someone who has just developed an interest in building websites or web applications,<br />
you may be interested in understanding this proverbial skeleton of a web page and how<br />
<strong>jQuery</strong> fits into the big picture.<br />
You may also want to become familiar with the concept of refactoring your code. On the next<br />
page, let’s take a brief look at how to construct a page using the minimum HTML code.<br />
60
Technical documentation is often written by “experts” for “experts,” who often skip the very<br />
basic, essential details. But that’s not how I see education. This book is written for everyone<br />
who is trying to understand JavaScript and <strong>jQuery</strong> programming at its very basic level.<br />
I started writing this book in late 2011. A lot has changed since then. The web started to move<br />
in the direction of mobile devices. User interfaces became important. But one thing remained<br />
the same. <strong>Understanding</strong> JavaScript is essential to understanding <strong>jQuery</strong>.<br />
Because <strong>jQuery</strong> is a JavaScript framework, it is important to understand that what you are<br />
learning about <strong>jQuery</strong> is essentially just the JavaScript syntax. Syntax in any programming language<br />
is simply a set of rules which defines how a program in that language should be written.<br />
JavaScript is a programming language in which everything is an object. I make references<br />
to this statement throughout my book. The main <strong>jQuery</strong> object itself is nothing more than a<br />
JavaScript object. All variables, functions, arrays, strings, numbers can also be treated as objects<br />
in JavaScript. But what is an object? An object is a concept that was created as part of the<br />
Object Oriented Programming paradigm (also known as OOP) developed decades ago. It was<br />
part of the evolution of programming languages as they were not always object-oriented.<br />
For now all you have to know is that the entire framework is a <strong>jQuery</strong> object. Objects can be<br />
used to execute functions “attached” to them. And understanding these functions are at the<br />
core of using <strong>jQuery</strong>. Even though CSS selectors are incredibly important, I will talk about<br />
CSS selectors later in the following sections of the book.<br />
What is JavaScript?<br />
JavaScript is a web programming language that was designed to add dynamic features to web<br />
pages. In the old days, we only had HTML and that was for making static websites with text<br />
and images.<br />
JavaScript allows us to make our websites come to life. We can add colors, change text, add or<br />
remove new elements to/from our page, etc. without having to refresh the page in the browser.<br />
And this dynamic nature of the web today is what makes it possible to develop web applications<br />
that react to user’s input.<br />
You probably have interest in <strong>jQuery</strong> because of one or more of the following:<br />
1. You have a college assignment that requires using JavaScript or <strong>jQuery</strong>.<br />
2. Your employer is asking to develop a dynamic feature like an image slider.<br />
3. You are a freelance web developer who wants to save time writing code.<br />
4. You know HTML, but you are interested in building dynamic web applications.<br />
5. You are a website creation vigilante who is passionate about making things.<br />
61
If this sounds like you, then you will benefit from this book.<br />
What Makes <strong>jQuery</strong> Worth Studying?<br />
Web browsers constantly evolve. Each browser (Internet Explorer, Firefox, Chrome, Safari,<br />
Opera, etc....) has its own implementation of JavaScript. At the microscopic level, some browsers<br />
don’t have features of some other browsers. This means that the programmer is responsible<br />
for making sure his code works in all browsers separately.<br />
<strong>jQuery</strong> simplifies JavaScript programming. It allows us to write JavaScript code (which is what<br />
<strong>jQuery</strong> essentially is) without having to worry about the program working correctly in different<br />
browsers. Write your <strong>jQuery</strong> code once and it is guaranteed to work most of the time in<br />
most popular browsers. This way you don’t have to test your JavaScript in different browsers<br />
separately. <strong>jQuery</strong> takes care of that for us.<br />
Using <strong>jQuery</strong> over vanilla JavaScript helps to save time writing your program. <strong>jQuery</strong> has an<br />
incredibly simple and intuitive syntax. It’s what JavaScript was supposed to be when it was<br />
developed.<br />
<strong>jQuery</strong> is a JavaScript framework that makes JavaScript programming easier. A framework is a<br />
collection of functions and utilities, like a swiss army knife. It’s a toolset containing an array of<br />
useful functions and easy ways to do rudimentary JavaScript tasks in an easy-to-use syntax.<br />
When it comes to HTML <strong>jQuery</strong> works exclusively with HTML tags by selecting them. You<br />
select what you need, and apply a function to what you just selected.<br />
Here are just a few basic examples of what you can do with <strong>jQuery</strong>:<br />
1. Dynamically remove (<strong>hide</strong>) all DIV elements using $(“div”).<strong>hide</strong>();<br />
2. Select all elements on the page using $(“*”); (the star selector.)<br />
3. Insert text or HTML dynamically into any other element by using $(“div”).html(“text”);<br />
4. Load a separate web page with ajax using $.ajax(url); call.<br />
5. Attach events to HTML elements without having to use tag attributes (like onclick, etc.)<br />
6. Get current browser version. It’s stored in <strong>jQuery</strong>.browser or simply $.browser.<br />
7. An easy to use syntax and functions for selecting complex sets of HTML elements.<br />
This list can go on and on. Well, it all sounds great, but what is the quickest way to start using<br />
<strong>jQuery</strong> on your website? In order to start using <strong>jQuery</strong> all you have to do is include it in the<br />
source code of the web page.<br />
Adding <strong>jQuery</strong> file to a web page is simple and will enable <strong>jQuery</strong> for that page only, not the<br />
entire site.<br />
62
Including <strong>jQuery</strong> In Your Webpage<br />
To include <strong>jQuery</strong>, first download the latest version at www.jquery.com and unzip or copy the<br />
file to the root directory of your website project (in other words, where your index.html or index.php<br />
file is.) They always update the file to the most recent version, so it’s essential to have<br />
the latest copy. It fixes bugs and improves performance.<br />
I go in detail about how to include <strong>jQuery</strong> in your webpage in my book which also speaks<br />
about increasing performance of your JavaScript code. But at the very basic level, <strong>jQuery</strong> is<br />
included into your web page by adding the following line in between HEAD tags on your page:<br />
<br />
<br />
<br />
Where “jquery-1.7.1.min.js” is the <strong>jQuery</strong> library file you downloaded. You can also specify<br />
a relative path such as js/jquery-1.7.1.min.js or (of course) you can specify the exact path, for<br />
example directly located on one of your websites:<br />
http://www.thisisyourwebsite.com/js/jquery-1.7.1.min.js<br />
That’s everything. Add that line and you are ready to start writing <strong>jQuery</strong> code inside of your<br />
webpage. But where exactly do we enter <strong>jQuery</strong> code?<br />
Where Do You Type <strong>jQuery</strong> Code?<br />
<strong>jQuery</strong> is nothing more than JavaScript. In fact, <strong>jQuery</strong> object is just a JavaScript function that<br />
we call over and over again to select HTML elements and do something interesting with them.<br />
This means that <strong>jQuery</strong> code will work only where JavaScript is allowed on a web page.<br />
1. Anywhere in a JavaScript file using .js extention. Right in between JavaScript code.<br />
2. Anywhere inside HTML attributes like onclick, onmouseover, onload, etc.<br />
3. Inside SCRIPT tags.<br />
Basically, anywhere you can write JavaScript code. That’s where you write <strong>jQuery</strong> code.<br />
63
Web App Initialization<br />
To initialize our web app we write code inside document ready event inside SCRIPT tag:<br />
<br />
<br />
$(document).ready()<br />
{<br />
/* Initialize your <strong>jQuery</strong> and JavaScript code here */<br />
}<br />
<br />
<br />
Writing HTML code to make website layouts is one thing. And you may already be familiar<br />
with that. But JavaScript web applications often require an initialization process. This is where<br />
you set all of your program’s variables default values. If it’s a game, this is the place where you<br />
reset score to 0, player lives to 3, and reset the game state, etc. If you are a web designer, this<br />
is where you reset your <strong>jQuery</strong> image slider, set it to display the default image and <strong>hide</strong> other<br />
slides for now. In other words, this is your website reset point.<br />
Calling <strong>jQuery</strong> Commands.<br />
We have two basic ways of calling <strong>jQuery</strong> functions<br />
1. Using the CSS selector syntax such as $(“div”) to select all div elements.<br />
2. Using <strong>jQuery</strong> library objects (variables or functions) like $.ajax(url) and $.browser.<br />
With regard to item 1 once we select an element or a group of elements, we can now use <strong>jQuery</strong><br />
functions on that selection (ignoring all the other HTML elements that were not selected).<br />
These functions we can use on selected HTML elements are at the core of the <strong>jQuery</strong> library.<br />
Let’s take a look at just a few of them:<br />
$(“div”).click( function(){ alert(“I was clicked.”); } );<br />
Attach a click event to selected element(s) and specify what should happen.<br />
In this particular case, we make an alert show up when ANY div element is clicked.<br />
Because remember, the “div” selector selects absolutely all DIV elements on your page.<br />
$(“div”).bind(“click”, function(){ alert(“I was clicked.”); } );<br />
Exactly the same thing as above, except using the bind (as in bind event to an element) In<br />
<strong>jQuery</strong> you can often do the same thing in a slightly different way.<br />
64
People who are reading this book come from all kinds of backgrounds and skill levels. I don’t<br />
mean to offend the intelligence of those who already understand the concepts explained below.<br />
But this is the necessary information that helps us understand <strong>jQuery</strong>. It is through understanding<br />
JavaScript basics.<br />
I know you might think: What is this $(“div”) and why are we typing that? Or what is this<br />
function() inside the second set of parenthesis? What you are seeing is the JavaScript syntax.<br />
The dollar sign ($) represents the main <strong>jQuery</strong> object, which is a JavaScript function. Parenthesis<br />
are used to pass parameters to that object/function. This is the legal JavaScript syntax.<br />
Remember that to use a function we must first define it.<br />
To define a function.<br />
function( parameters ) { ..entre code here to define what this function does.. };<br />
To execute that function:<br />
function( parameters );<br />
The parameters can be passed to a function one by one, separated by comma. Parameters turn<br />
into usable variables inside the function. So, how does all of this relate to <strong>jQuery</strong>? Let’s take a<br />
look!<br />
The dollar sign $ or <strong>jQuery</strong> are the names of the same function. They are equal each other:<br />
$ = <strong>jQuery</strong> = function( parameters ) { /* definition of entire <strong>jQuery</strong> library */ }<br />
In the two examples way above there, where I am using $(“div”), here is what happens. As you<br />
can see we first execute the $ function which is the main <strong>jQuery</strong> object. Everything in JavaScript<br />
is an object. This is why I refer to functions as objects interchangeably. You’ll find out<br />
what an object is later on in my future newsletters. For the purpose of this tutorial it is not<br />
necessary.<br />
The paremeter we are passing to the <strong>jQuery</strong> function is “div”. We use double quotes because we<br />
are passing a string of text. We are naming a literal HTML tag using a text-based name (also<br />
called a string of text, or simply a string). In programming a string is often referred to a line of<br />
text (with or without spaces), in other words a string of characters like a,b,c, etc.<br />
Had we not used the double quotes that would tell <strong>jQuery</strong> that we are passing a variable called<br />
div. For example, then, our code would look like $(div). But you see, when double quotes are<br />
not used, it tells JavaScript that there is a variable called div, not a string of text!<br />
65
In JavaScript, we can define variables as follows:<br />
var tag = “div”;<br />
So we just created a variable called tag, and assigned the string value of “div” to it. It could be<br />
anything “abc” or “I’ll believe it when I see it.” It does’t matter. We just created a variable containing<br />
a string of text.<br />
Now that we have this variable defined, calling the following code:<br />
$(tag);<br />
...without double quotes would be the exact same thing as calling:<br />
$(“div”);<br />
It’s the same thing because that’s what the variable tag is defined as - as the literal string “div”.<br />
It’s like they switched places :-) So that’s an example of passing a variable to a function.<br />
Had we not defined variable tag as “div” and said $(tag) then JavaScript would give us an error<br />
and say that tag is undefined.<br />
<strong>jQuery</strong> offers us many stand-alone functions that stem from the main <strong>jQuery</strong> object (they are<br />
attached to it) Stand-alone functions do not require elements to be selected. For example:<br />
$.ajax(“webpage.html”);<br />
This function simply calls the ajax method to dynamically load a web page and return its content<br />
as a result (commonly known as function’s return value.)<br />
However, CSS plays an even bigger role in writing <strong>jQuery</strong> code. In fact, selecting HTML elements<br />
using CSS selectors is an extraordinarily important function of <strong>jQuery</strong>.<br />
I dedicate a relatively large part of the book to detailed explanations of CSS selectors. But before<br />
we get to them let’s take a look at <strong>jQuery</strong> as a JavaScript statement.<br />
66
<strong>jQuery</strong> as a JavaScript Statement<br />
<strong>jQuery</strong> offers a simple syntax to execute functions, attach events to HTML elements and simplify<br />
JavaScript programming. However, when it comes to studying <strong>jQuery</strong> from absolute zero<br />
there is a problem. Original documentation is written by people who created <strong>jQuery</strong>. It’s therefore<br />
written in a language that is suitable only for JavaScript experts.<br />
Because elegance of <strong>jQuery</strong> syntax is accessible to anyone with enough interest to learn website<br />
script programming, it’s possible to learn <strong>jQuery</strong> the wrong way using the trial and error<br />
method.<br />
The purpose of this section of the book is to help you understand the fundamental knowledge<br />
that is skipped from pretty much most tutorials I’ve seen online. And these principles are so<br />
important to understand, especially if you are still studying JavaScript.<br />
The Basic Structure of <strong>jQuery</strong> Syntax<br />
Let’s consider the following example:<br />
$(“div”).bind(“click”, function() { ... } );<br />
If you are an experienced programmer you may find delight in this simplicity. But what if you<br />
just started studying <strong>jQuery</strong> and you don’t know anything about JavaScript? All of a sudden,<br />
even the simplicity of <strong>jQuery</strong>’s syntax is not so simple anymore. Here we select all div elements<br />
on the web page and attach (bind) the onclick event, represented by the literal string “click,”<br />
which is an alias to JavaScript’s onclick event (or HTML attribute.) It looks simple to the untrained<br />
eye.<br />
But let’s see what it looks like to someone who understands principles of JavaScript programming<br />
involved in this code:<br />
67
As mentioned above, to an experienced programmer, this is pure bliss. A syntax that combines<br />
so many complex principles into one line of code.<br />
But what does a beginner see when he looks at this code? A beginner is faced with a dilemma,<br />
often thinking: Well, that is just how it works, so I simply must write it this way. But this is<br />
an incorrect way of thinking about programming. You’d simply end up memorizing the order<br />
in which the symbols and signs (such as the $ sign, dots, brackets, etc...) are written, without<br />
actually understanding syntax.<br />
Let’s do another example which will try to explain the syntax of <strong>jQuery</strong>’s animation function.<br />
The function animate() is used when we want to dynamically change a specific property of an<br />
HTML element over a period of time specified in milliseconds. Let’s take a look:<br />
$(“#target”).animate({ width: “100px” }, 1500, “linear”);<br />
In order to help us understand what’s going on here, let’s take a look at this diagram:<br />
It’s easy to simply memorize. But as you can see, there is a lot going on even in a basic example<br />
of <strong>jQuery</strong> code. It makes sense then that there should be educational material that sheds some<br />
light on the inner workings of JavaScript. Many online tutorials focus on the functionality, but<br />
not on understanding of the language itself. In my understanding, this isn’t the proper way of<br />
studying a computer language.<br />
We already know what “#target” is. It is a CSS selector that selects an arbitrary HTML element<br />
whose id is “target”. But JSON notation is new. On the next page we will take a look at what<br />
JSON is.<br />
68
Web Application Template<br />
Click on “View Source” on this page in your browser to see the structure of the HTML file:<br />
www.learnjquery.org/book/sourcecode/1.000.starting-point.html<br />
This code will be used as the starting point throughout the course of this book. All demos and<br />
samples will be built around this example as the starting point.<br />
This simple example demonstrates something very important. It’s an example of organized<br />
code – an essential element of a well-written computer program.<br />
In particular, the HTML, CSS and JavaScript source code is divided into separate external files.<br />
Namely, program.js and program.css are two separate files. When starting your own project,<br />
it’s wise to rename these files to something which describes your program.<br />
Making a habit of starting a new project with this template is a good idea. It allows us to work<br />
with each individual part of your program separately, isolating a current problem.<br />
Avoid including CSS and JavaScript code internally inside the same HTML file whenever it is<br />
possible. If it is possible to make a file to be linked externally, make it external. Do not write all<br />
of your HTML, CSS and JavaScript in a single file. This helps browsers cache your application.<br />
Remember that while sticking to this rule is important, certain situations force us to write JavaScript<br />
or CSS code inside the same file. To single out code into separate files is certainly not<br />
a law and if you absolutely must write CSS or JavaScript in the same file then you can.<br />
Generally, placing different parts of the code into different files will help you stay organized<br />
and become more efficient at writing your program. It will help you save time in the long run<br />
especially as the size of your program increases.<br />
Dividing your code into separate sections is called code refactoring. Refactoring your code<br />
will make web programming simple, making it easy to focus on each file one at a time, instead<br />
of having to browse up and down the same source code file all the time.<br />
The source code includes the following items:<br />
1. js/jquery-1.7.1.min.js and js/jquery-ui-1.8.js are included externally.<br />
2. $(document).ready is included as a place to initialize all of your <strong>jQuery</strong> code.<br />
3. CSS reset code helps us to reset default CSS properties for all browsers.<br />
69
Including <strong>jQuery</strong> In Your Source Code<br />
In my projects I usually allocate a special space for all of my JavaScript files. I put all of the<br />
files ending in .js into the folder “js” in the root directory of my application. Because <strong>jQuery</strong> is<br />
written in JavaScript it has an extention of .js. So I naturally like to place it inside the “js” folder<br />
located in the root folder of my web application.<br />
JavaScript files are inserted into a web project at the very top of the HTML page between the<br />
two opening and closing HEAD tags:<br />
This is where you specify the location of the <strong>jQuery</strong> .js file<br />
<br />
<br />
<br />
<br />
This is my website content<br />
<br />
As you may already know, we use the SCRIPT tag to include JavaScript files. You can download<br />
the most recent version of <strong>jQuery</strong> file from their website www.jquery.com directly from<br />
the homepage. As of this writing, the most recent version of <strong>jQuery</strong> is version 1.7.1<br />
But you don’t always have to download <strong>jQuery</strong> just to add <strong>jQuery</strong> functionality to your page.<br />
Live Internet locations are also available. Simply include them using the SCRIPT tag:<br />
Hosted by <strong>jQuery</strong><br />
code.jquery.com/jquery-1.7.1.min.js<br />
Hosted by Google<br />
ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js<br />
Hosted by Microsoft<br />
ajax.aspnetcdn.com/ajax/<strong>jQuery</strong>/jquery-1.7.1.min.js<br />
One of the reasons you would want to let <strong>jQuery</strong>, Google or Microsoft host your <strong>jQuery</strong> file<br />
is for the benefit of improved latency. They have no choice but to offer the fastest CDN access<br />
to everyone in the world. The web host you are using may limit the number of simultaneous<br />
HTTP requests made to the server by your site. The <strong>jQuery</strong> files hosted at these locations do<br />
not have the same limitations because they can be accessed by any site at any time.<br />
Using your server’s cache configuration you can make sure that each unique visitor downloads<br />
the <strong>jQuery</strong> library only once. Next time they return to your website, the cached version will be<br />
used. Unfortunatelly server-side cache configuration is not covered in this book.<br />
70
Include <strong>jQuery</strong> Locally<br />
What if you are working on a local computer and it’s not connected to the Internet? Sure<br />
enough you can add <strong>jQuery</strong> by including the framework file directly from a location off the<br />
root folder of your project. Just make sure the file is actually located there:<br />
project_root_folder/js/jquery-1.7.1.min.js<br />
71
Including <strong>jQuery</strong> as an External CDN-based Files<br />
Let’s take a brief look at the basic properties of an externally included file:<br />
1. An external file is a file that is separate from your main HTML file.<br />
2. An external file can be hosted on the same host. In most cases, it is.<br />
It is not necessary, however, for an external file to be located on the same host as your web<br />
page. You can add an external JavaScript file from a separate website and it will still be included<br />
as part of your HTML page. The code will execute.<br />
The <strong>jQuery</strong> locations discussed on the previous page are hosted by Google, Microsoft and the<br />
<strong>jQuery</strong> project itself. They are offered in two flavors HTTP and HTTPS. The latter stands for a<br />
secure connection with SSL.<br />
The subject of the HTTP protocol and secure connections will not be discussed in this book.<br />
However, you must know about Relative URL References with regard to including <strong>jQuery</strong><br />
from CDN locations using either the HTTP or HTTPS protocols.<br />
For various reasons you may be interested in including either HTTP or HTTPS version of the<br />
hosted file from one of the discussed CDNs.<br />
What is a relative reference? It allows us to include external file without mentioning the absolute<br />
location such as www.mywebsite.com/js/script.js. There are similar rules at work when<br />
choosing either HTTP or HTTPS protocols, too.<br />
Some pages on your website will be using the HTTP protocol. Others, HTTPS. In order for<br />
our page to include the right protocol automatically, and according to the HTML specification,<br />
we can use the double slash // symbol, as in:<br />
<br />
Notice the leading // symbol. It means the correctly matched protocol will be used.<br />
This is useful, because, for example, if you were forcing the fixed HTTPS protocol in an externally<br />
included file, on a web page that was itself using HTTP, you would encounter a “mixed<br />
content” security message. The // also helps us properly cache the file. Note that HTTPS can<br />
never be cached.<br />
The golden rule is whenever an external file is offered in HTTP and HTTPS flavors, use only<br />
the // when including it, instead of http:// or https://<br />
This method can also improve page load speed in some cases.<br />
72
How To Always Include the Latest Version of <strong>jQuery</strong><br />
Working with <strong>jQuery</strong> for a long time you notice something interesting.<br />
The <strong>jQuery</strong> team constantly churns out new versions of the framework containing important<br />
bug fixes. Trying to always keep your version up to date can skip your attention. A new version<br />
becomes available, but your programs will no longer be using the advantages of the most<br />
recent version.<br />
There is a way to make this process automatic. Just like in the previous examples, this can be<br />
done by including the most recent version of <strong>jQuery</strong> from a CDN hosted by someone else.<br />
Here is an address that always points to the most recent version of <strong>jQuery</strong>:<br />
http://code.jquery.com/jquery-latest.min.js<br />
When fixing bugs, the <strong>jQuery</strong> team puts a lot of effort into making different adjustments to<br />
their code. All for the benefit of greater performance and better implementation across all<br />
browsers. Things change. When you are working on your code, you are writing it for the currently<br />
available version of <strong>jQuery</strong>.<br />
Let’s say you are taking advantage of adding the most recent version of <strong>jQuery</strong> automatically,<br />
using the CDN address displayed above. Imagine that the <strong>jQuery</strong> team has committed a fundamental<br />
change to their framework and released it under the most recent version. Without<br />
you knowing, your website has now automatically switched to that new version of the framework.<br />
Even though the new version is an improvement, some of your code may just not work after<br />
that adjustment anymore, or even break the entire JavaScript execution flow. It all depends on<br />
which parts of the framework were modified and how.<br />
And that’s how JavaScript works. It stops working after encountering one error. next commands<br />
will not run. Dynamic parts of your website are brought to a halt! And nobody knows<br />
why until the problem is revealed in Firebug.<br />
If you choose this road, always keep an eye on the latest version release. Be ready to test your<br />
code every time a new version arrives. You may get lucky. But then again you may not. The<br />
choice, in the end... is yours.<br />
73
Including <strong>jQuery</strong> UI<br />
In the Starting Point “skeleton” HTML file discussed in the beginning, we have also externally<br />
included the <strong>jQuery</strong> UI file js/jquery-ui-1.8.js<br />
<strong>jQuery</strong> UI is yet another library written using the original <strong>jQuery</strong> framework. <strong>jQuery</strong> UI will<br />
not work if the <strong>jQuery</strong> framework is not included first.<br />
With regard to this book, <strong>jQuery</strong> UI will be mostly used for animation easing styles which are<br />
defined by Bézier curve algorithms.<br />
<strong>jQuery</strong> UI is used for much more than animation easing styles. You can use it to create interactive<br />
widgets like buttons, sliders, tabs, and so on...<br />
It really makes no sense describing everything that it does in this book, because the official<br />
<strong>jQuery</strong> UI website www.jqueryui.com/docs/Getting_Started is an excellent manual that contains<br />
a complete walk-through of every single feature. It has a phenomenal navigation and easy<br />
to follow instructions.<br />
I recommend coming back to that page after you have learned the basics of <strong>jQuery</strong>.<br />
In order for some examples from later chapters of this book to work, <strong>jQuery</strong> UI library must<br />
be included. I like to always include it in my projects because I just might need it.<br />
74
CSS Selectors<br />
This section is about CSS Selectors, the importance of knowing what DOM is and learning to<br />
select elements of all kinds in different ways.<br />
CSS selectors play crucial part in <strong>jQuery</strong> development. Many people are comfortable with just<br />
learning a few selectors. But using selectors in combination with <strong>jQuery</strong> functions further enable<br />
us to make complex selections. For example next, prev and parent functions let us quickly<br />
jump from one HTML element to the next.<br />
You want to learn as many selectors as possible if you want to increase your productivity. But<br />
don’t learn them all at once. Experiment with one selector at a time, and build your knowledge<br />
on your past experience.<br />
Let’s consider some of the very basic <strong>jQuery</strong> selectors. The green areas indicate the area of a<br />
web page being selected by the corresponding <strong>jQuery</strong> code displayed below each example:<br />
$(‘body’); $(‘#orange’); or<br />
$(‘div#orange’); or<br />
$(‘body div#orange’);<br />
$(‘#orange’).parent();<br />
In the first example we select an element by tag name BODY. In this case, we are selecting the<br />
entire body tag. Notice that the children of BODY are not selected only BODY is.<br />
The second example uses the # symbol which selects elements by id attribute. In this example<br />
when id = “orange”. All three selectors in this example do exactly the same thing but with a<br />
different level of accuracy. #orange selects any element with that id but div#orange selects a<br />
div element with that id. Remember that there can be only one unique id per element.<br />
Third example shows how we can select BODY by referring to it as the parent of a child within<br />
it using the function parent(). The DIV in this instance is a child of the parent tag BODY.<br />
The function parent() is part of a set of functions for traversing nested HTML tags within the<br />
DOM (Document Object Model). Other traversing functions exist such as next() and prev()<br />
which will be discussed shortly. CSS Selectors operate on the DOM structure of the entire<br />
document starting at the very top. $(“*”) selector selects all tags, even ones above .<br />
75
What Kind of Elements Can You Select?<br />
<strong>jQuery</strong> selectors can select pretty much any HTML element. And if you understand the basics<br />
of DOM (Document Object Model), you are at a great advantage. Using your knowledge of<br />
DOM and <strong>jQuery</strong> selectors together can significantly reduce the time you spend developing<br />
dynamic JavaScript applications.<br />
Here is the basic idea of the DOM. It looks like a tree. The HTML code equivalent of this<br />
DOM structure is displayed below the diagram.<br />
<br />
<br />
A Clockwork Orange<br />
<br />
<br />
A Movie<br />
By Stanley Kubrick<br />
<br />
<br />
76
The DOM is pretty easy to understand. It is very useful for thinking about your <strong>jQuery</strong> selectors.<br />
But it’s surprising how many people ignore it. Respect the DOM. Don’t ignore it.<br />
CSS Selector code is the first parameter of the main <strong>jQuery</strong> object. Let’s quickly take a look at<br />
the definition again:<br />
<strong>jQuery</strong> = function(selector, context) { /* Library code */ }<br />
The selector argument is one of the most frequently used parameters of <strong>jQuery</strong>. Many people<br />
don’t even realize that there is a second argument that they can pass, called context. I’ll get<br />
back to that later in this tutorial.<br />
The selector parameter specifies the CSS selector code. Once the element in question is selected,<br />
we can run a function on it.<br />
<strong>jQuery</strong>(‘div’).<strong>hide</strong>();<br />
This will select all DIV elements within the BODY branch of the DOM.<br />
If multiple elements have been selected, this function will run on all selected elements. This<br />
means, it will <strong>hide</strong> all DIV elements in BODY, even though BODY is not even a part of the<br />
definition. It is assumed that the first selector refers to the BODY branch in DOM. We can<br />
explicitly specify BODY in our selector, as you will see in the examples below for the sake of<br />
being complete. But it is not always necessary.<br />
Common CSS Selector Examples<br />
Let’s take a look at some of the most common <strong>jQuery</strong> selectors that you are probably going to<br />
be using all the time.<br />
Probably one of the most common selectors is the # symbol. It stands for selecting a DIV with<br />
an ID specified immediately after the # symbol.<br />
<strong>jQuery</strong>(‘#dog’).<strong>hide</strong>(); // Select an element that has ID of “dog”, and <strong>hide</strong> it<br />
<strong>jQuery</strong>(‘div#dog’).<strong>hide</strong>(); // Select DIV element that has ID of dog, and <strong>hide</strong> it<br />
We can always refer to an element with an ID of “dog” as #dog in our <strong>jQuery</strong> selector. If we<br />
want to be specific and select a DIV with an ID of “dog”, we can use “div#dog”. Of course, this<br />
is a matter of semantics. Following the rule that there could (or should) be only one element<br />
with a unique ID per webpage, it probably makes no sense prefixing the selectors that start<br />
with # with the name of an element.<br />
77
To traverse the DOM and make sure that we are selecting the right thing, we can use the<br />
SPACE ( ) operator. The space operator lets DOM know exactly which branch we want to traverse:<br />
// Hide all DIVs inside BODY, but not BODY itself<br />
<strong>jQuery</strong>(‘body div’).<strong>hide</strong>();<br />
// Hide all DIVs inside first DIV child of BODY, but not DIV child itself<br />
<strong>jQuery</strong>(‘body div div’).<strong>hide</strong>();<br />
// Hide all DIVs inside first DIV child of BODY whose id is #secret<br />
<strong>jQuery</strong>(‘body div#secret div’).<strong>hide</strong>();<br />
Note that none of the elements before the last space are actually selected. Only the last one is.<br />
The values before the last space simply indicate the DOM path to traverse, but the path itself is<br />
not selected, only the last element in the path.<br />
CSS Selector Reference<br />
The following diagrams visually explain how many <strong>jQuery</strong> CSS selectors work. Print it out,<br />
you may find it as a useful reference to keep on your desk. Green indicates selected result.<br />
In the first two examples we select arbitrary elements, one with id “clockwork” and another<br />
with id “orange”. We then use the prev() and next() functions respectively to traverse back or<br />
forward within the parent element. Function prev() steps one element back within the same<br />
hierarchy. Function next() steps one element forward. The third example doesn’t select anything<br />
at all. Why not? This is because there are no previous elements before the element with<br />
id “orange”. The prev() function will not select the parent of current hierarchy.<br />
78
Using Colon-based CSS Selectors<br />
In this section I want to explore the colon (:) in <strong>jQuery</strong> selectors. The colon is like a mini<br />
helper tool that lets us converge to the element we are searching for with greater precision.<br />
Below I list most of the cases in general when the colon is used:<br />
Colon-based CSS selector Practical example What it selects<br />
:first<br />
:last<br />
:even<br />
:odd<br />
:eq(index)<br />
:gt(N)<br />
:lt(N)<br />
:not(selector)<br />
:header<br />
:animated<br />
:contains(text)<br />
:empty<br />
:hidden<br />
:visible<br />
$(“p:first”)<br />
$(“p:last”)<br />
$(“tr:even”)<br />
$(“tr:odd”)<br />
$(“ul li:eq(3)”)<br />
$(“ul li:gt(3)”)<br />
$(“ul li:lt(3)”)<br />
$(“input:not(:empty)”)<br />
$(“:header”)<br />
$(“:animated”)<br />
$(“:contains(‘clockwork’)”)<br />
$(“:empty”)<br />
$(“p:hidden”)<br />
$(“table:visible”)<br />
The first p element<br />
The last p element<br />
All even tr elements<br />
All odd tr elements<br />
The fourth element in a list (index starts at 0)<br />
List elements with an index greater than 3<br />
List elements with an index less than 3<br />
All input elements that are not empty<br />
All header elements h1, h2 ...<br />
All animated elements<br />
Tag contains text ‘clockwork’<br />
All elements with no child (elements) nodes<br />
All hidden p elements<br />
All visible tables<br />
I chose what I thought were the most important colon-based selectors. It’s not that colonbased<br />
selectors are used less frequently than selectors like # (id) and . (class) but it’s that they<br />
are used to compliment the id and class selectors.<br />
To see the full list - http://api.jquery.com/category/selectors/<br />
The colon selectors are often used with input-based elements when working and manipulating<br />
radio buttons, the select and option elements, check boxes and textareas.<br />
The number of the colon-based selectors can overwhelm someone who is just starting to learn<br />
<strong>jQuery</strong>. My suggestion is to choose one to practice with until you fully understand how it<br />
works and then move on to the next. In fact, if you do this for a few days, you’ll get them all<br />
down in no time.<br />
I Selected an Element. What’s Next?<br />
<strong>jQuery</strong> gives us an easy way to select HTML elements. But what’s next? Just selecting an element<br />
is like turning the ignition on and just sitting in the car waiting for something to happen.<br />
In order to get a greater insight into this, let’s take a brief look at objects and JavaScript.<br />
Sometimes we want to work with the this object which refers to the object that your Javascript<br />
program flow currently has focus on, during the execution time of your script.<br />
80
Here is a basic inline CSS example of the this keyword in action:<br />
Iris<br />
I highlighted the part of top interest in yellow. This is the inline JavaScript code located within<br />
the onclick attribute of the arbitrary DIV element. Before I talk about this example in the context<br />
of <strong>jQuery</strong> selectors I need to mention one important thing.<br />
Don’t worry if you have never seen the this keyword before. Or if you have seen and used it<br />
before but didn’t understand where exactly it comes from. I don’t blame you. Learning about<br />
the this keyword from an inline JavaScript example like this is wrong. Yet, many inline JavaScript<br />
examples use the this keyword without explaining what it actually means and how<br />
to think about it. For now, just know that the this keyword is a self-reference to the object it is<br />
used within. In this case the DIV with id “iris.”<br />
HTML is a very fluid language to work with. Elements are typed in, and then, as if by a swing<br />
of a magic wand a block or a table representing the website layout appears in the browser.<br />
But what not many people know is that every time an HTML element is defined, inside the<br />
program something that is called an object is created to refer to that element. The entire<br />
HTML page can be referred to by using these objects alone.<br />
As you place more elements within elements, these objects also become nested within the<br />
structure of the entire document. This is called DOM or Document Object Model.<br />
What happens when we select HTML elements using one of the <strong>jQuery</strong> selectors? It’s important<br />
to think about DOM and the this keyword when discussing CSS selectors because the<br />
<strong>jQuery</strong> selectors traverse DOM structure to find the right element.<br />
You will learn much more about JavaScript objects and understand what they are later in the<br />
book. But for now let’s return to our discussion of CSS selectors.<br />
In the context of the example above, the this object refers to the element it is used in. In other<br />
words, because onclick attribute is inside the DIV element identified with id “iris,” the this<br />
keyword refers to the object of that DIV element. Intuitively then, we can use the style object<br />
to modify the background color of the element and se it to “gold”, which is a pre-defined<br />
HTML color name. It could have been red, green, blue, etc. or even #FF0000. The this keyword<br />
allows us to apply an HTML style to itself, the DIV element it refers to.<br />
Thinking that the this keyword was designed to be used as inline JavaScript only would be<br />
a mistake. The origin of the this keyword has nothing to do with inline JavaScript. It has to<br />
do with the concept of objects as used in computer science in general and more importantly,<br />
within a computer program itself. The onclick attribute is simply one of the places where it’s<br />
allowed for us to write JavasSript code.<br />
81
We just used inline JavaScript to add new functionality to a DIV element. Clicking on this DIV<br />
element will now turn its background to gold color or any other color of your choice.<br />
The same exact effect can be achieved by rewriting the inline JavaScript code within the onclick<br />
attribute. Let’s do that using <strong>jQuery</strong> this time:<br />
$ is the main <strong>jQuery</strong> library Object<br />
A few things are happening here:<br />
Which CSS style to modify? What to change it to?<br />
onclick = “$(this).css(‘background’, ‘gold’);”<br />
This HTML element “css” is one of many <strong>jQuery</strong> functions<br />
1. We start by calling the $ function, which is just another variable name for <strong>jQuery</strong>.<br />
2. The this keyword is passed as an argument to the <strong>jQuery</strong> function to select current DIV.<br />
3. Function css is called. It is one of the many functions offered by <strong>jQuery</strong> library.<br />
4. Two arguments are passed to the css function:<br />
a. The argument “background” tells the css function that we want to modify background.<br />
b. The argument “gold” tells the css function to change its color to gold.<br />
Here we pass the this keyword as an actual parameter directly to the <strong>jQuery</strong> object. The entire<br />
JavaScript statement highlighted in yellow can be translated as:<br />
When it is clicked, change the background color of this DIV to gold.<br />
Before moving on to the next subject we need to understand one more thing. In the beginning<br />
of this section we discussed that CSS can be selected using all kinds of different selectors represented<br />
by a string of text. For example the string body would select the HTML element body<br />
which encompasses the entire page. Something like #orange or div#orange would select any<br />
element whose id is orange or a DIV element whose id is orange, respectively.<br />
Remember that the dollar sign function is just a JavaScript function like any other. And in this<br />
example, instead of passing a string we are passing the this object to the same exact function,<br />
the dollar sign. And it still works. The parameters of a JavaScript functions are typeless. The<br />
type of the argument is ignored.<br />
If the this object is passed, <strong>jQuery</strong> is able to recognize that automatically and works directly<br />
with the object itself. When, on the other hand, it sees that a string is passed to it, it first determines<br />
which HTML elements this string describes and only then finds the appropriate object<br />
or objects to select directly from the DOM structure of your page.<br />
82
Because the DIV element has ID of “iris”, the same exact effect could be achieved by writing<br />
the following <strong>jQuery</strong> command. This command is not called from within an onclick event. In<br />
fact, it can be called from anywhere where JavaScript code is allowed in an HTML document.<br />
$(“#iris”).css(‘background’, ‘gold’);<br />
This command will select any HTML element whose id “iris”. Notice the # symbol telling the<br />
selector to find any element with that id. The css part remains exactly the same. Just as in the<br />
previous example css is the function we want to apply to selected elements. Whatever was selected<br />
will now be liable for receiving the new css style.<br />
<strong>jQuery</strong> offers a long list of functions that can be applied to the selected elements. These functions<br />
make it easy to apply CSS styles and even dynamically animate the size, position or colors<br />
of an element. You can <strong>hide</strong> elements, change their CSS properties; as in the example above<br />
or attach events to elements.<br />
On the previous page we took a look at how using inline JavaScript we could add <strong>jQuery</strong> code<br />
to an attribute of an HTML element. We used the onclick attribute to change something about<br />
that element when it was clicked. In other words we attached a user event to that element.<br />
Using <strong>jQuery</strong> it is possible to attach an onclick even to any element without having to use<br />
inline code. This is acheived using bind and unbind functions. The modern version of <strong>jQuery</strong><br />
library suggest that we should use the functions called on and off. But that’s like getting a little<br />
ahead of where we are right now. Events are explained later on in the book. For now, just know<br />
that <strong>jQuery</strong> is a powerful library that is not limited to merely changing CSS styles.<br />
<strong>jQuery</strong> gives us access to a number of very helpful functions. But what are they? Let’s take a<br />
look at some of the most popular <strong>jQuery</strong> functions.<br />
Function Practical example What it does<br />
css(style, value)<br />
<strong>hide</strong>()<br />
show()<br />
prev()<br />
next()<br />
parent()<br />
html()<br />
text()<br />
animate()<br />
css(‘background’, ‘red’)<br />
$(‘div’).<strong>hide</strong>()<br />
$(‘div’).show()<br />
$(‘div’).prev()<br />
$(‘div’).next()<br />
$(‘div’).parent()<br />
$(‘div’).html(‘new’)<br />
$(‘div’).text(‘new text’)<br />
$(‘div’).animate({left: “100px”}, 1000)<br />
Apply a CSS style to an element.<br />
Hide all DIV elements. As in display:none;<br />
Show all DIV elements. As in display:block;<br />
Go to previous child within same DOM branch.<br />
Go to next child within the same DOM branch.<br />
Go to the parent of the currently selected element.<br />
Replace the actual HTML content of an element.<br />
Replace the content of an element with text.<br />
Dynamically move the element to left: 100px;<br />
83
This table lists only some of the functions. I tried to choose some of the most important ones<br />
that I myself use often. There are many more functions related to each specific sub-group of<br />
tasks: events, CSS, visual effects, animation, Ajax, utilities and more.<br />
Making Complex Selections<br />
I want to conclude by showing you an example of a complex CSS selection. The idea came<br />
from a real project I was working on where I wanted to update a table cell, based on whether<br />
any text located in an input field in an adjacent table cell has been changed. I wanted to update<br />
the “has been edited” state every time the input in any table cell lost focus.<br />
This would then change the text in an adjacent table cell from ok to ch, an indicator that “the<br />
value has been changed for this element”. This way later I could simply grab (again, using<br />
<strong>jQuery</strong>) only input fields that have been changed to new values and send it to the script to update<br />
them, while ignoring values that were unchanged.<br />
<br />
<br />
$(document).ready(function()<br />
{<br />
$(‘table td:nth-child(3) input’).change(function()<br />
{<br />
$(this).parent().prev().html(‘ch’);<br />
});<br />
});<br />
<br />
<br />
<br />
Item Status Input<br />
First Name ok <br />
Last Name
After selecting all of these input boxes, we attach the change event to it, and assign it a function.<br />
Whatever goes inside the { ... } brackets of that function will execute every time the input<br />
field loses focus (when you click out of it, in other words onblur).<br />
Note that the nameless function closure inside the change(...) event will actually be assigned to<br />
each individual cell in the third column of this table, one by one (the function is assigned for<br />
each table cell in the 3rd column). This is what the table td:nth-child(3) input selector does. It<br />
goes into each cell of the third column one by one, using each cell as the starting point.<br />
We use the <strong>jQuery</strong>’s parent() function. The parent of the selected input box is the TD cell in<br />
which it is located.<br />
We now use the prev() function on parent, to go back one TD cell. This is because the previous<br />
child of the TD in which the input box is in, is the “status” TD. That’s the one we need to update.<br />
This means we are now in the “status” TD cell.<br />
Let’s modify the status TD cell with a new message, because the input has been modified for<br />
that row’s input box. We use html(‘ch’) function. The default HTML in the status cell is “ok”,<br />
and now we change it to “ch” (for: it has been changed!), or also known as “dirty” in the software<br />
developer circles.<br />
Of course you can get creative and do whatever you want, change the cell’s background color<br />
by using css(‘background’,’ red’), or even insert a custom image icon indicating a “changed”<br />
state. The point is that by using DOM’s element associations, we were able to traverse the<br />
DOM tree backwards and into the element we needed to update. And all without using spiderweb<br />
code.<br />
I believe that this example illustrated how much more simple your Javascript development<br />
can be using <strong>jQuery</strong>. Try to stick to similar ideas presented here. Traverse fields using their<br />
children and parents, instead of directly accessing them by ID. This can be extremely powerful<br />
technique and keeps your code clean and easy to edit.<br />
85
More About CSS Selectors<br />
Selecting things is at the very core of <strong>jQuery</strong> programming. Even though the previous chapter<br />
has already covered <strong>jQuery</strong> CSS Selectors there is much more to selecting HTML elements.<br />
Selecting Things: A Bird’s Eye View<br />
Selecting things doesn’t have to be complicated. However, there are many cases when the<br />
HTML is just way complicated. In many instances, people rush to assign many IDs or CLASSes<br />
to everything and go from there.<br />
The ID and CLASS attributes are not the best tools in this situation. In order to swiftly navigate<br />
the DOM tree structure, <strong>jQuery</strong> presents us with very neat tools. This tutorial will outline<br />
some of the most effective selectors to use in many common situations.<br />
At first, I started this tutorial with the focus only on input elements such as input, textarea,<br />
checkbox, radio button and select/option tags. But eventually as I continued updating it, it<br />
evolved into something much more.<br />
I still cover input elements at the bottom of his page, but I’d like to also talk about many other<br />
ways in which you should be selecting your elements. The best idea is to go through them one<br />
by one, and follow these clear diagrams below, that I think really make a good point of what<br />
each type of a selector will do.<br />
Once you memorize these ways, you will never want to go back to your old ID and CLASS attributes.<br />
One of the reasons for this is that each element already has a name - it’s tag name.<br />
<strong>jQuery</strong> allows us to refer to these tags by their name, and in some cases we can refer to them<br />
by not even using the name or ID of an element we want to select. How is this possible? Let’s<br />
compare the most common mentality of a <strong>jQuery</strong> enthusiast to one of a more experienced<br />
programmer.<br />
The main difference here is that when just starting out people tend to assign ID and CLASS attributes<br />
to everything. Is this the right way of doing things?<br />
Figure 1. explains mentality of the beginner <strong>jQuery</strong> programmer because everything is assigned<br />
an ID (and in many other cases a class, though, this is not shown on the diagram).<br />
Why is this a popular mentality of someone who just started out using <strong>jQuery</strong>? Well, it’s probably<br />
because they only learned how to select elements by ID or a Class name and refused to<br />
learn other types of selections one can make using advanced selectors and DOM traversal<br />
techniques that <strong>jQuery</strong> has in its arsenal.<br />
86
Figure 1<br />
Mentality of a beginner <strong>jQuery</strong> programmer.<br />
Everything has an ID. Sometimes<br />
even elements that don’t need them.<br />
Figure 2<br />
Mentality of an experienced <strong>jQuery</strong> programmer.<br />
It’s a clean slate, and there are<br />
different ways to get to elements. Not<br />
every element deserves an ID.<br />
What’s up with the “blank” mentality in Figure 2? A more experienced <strong>jQuery</strong> developer will<br />
look at the DOM as a clean slate. There is no need to assign an ID to every single element just<br />
to refer to it. In fact, this is possible because you can select any element without assigning a<br />
single ID or CLASS attribute to them.<br />
But at the same time, we know that referring to an element by ID is the fastest way to select<br />
an element. We have already discussed how you can use context, the second parameter of the<br />
<strong>jQuery</strong> ($) function to select a proper context and speed up your <strong>jQuery</strong> code. So, IDs should<br />
not be completely avoided. But they should not always be considered as the only method of<br />
element identification either.<br />
Because of this...it should be understood that a versatile <strong>jQuery</strong> programmer must create a<br />
balance between the two mentalities, not to ignore one of them completely. However, he or she<br />
must first consider Figure 2 and ask these questions:<br />
1. Does assigning an ID to an element in your DOM really improve your DOM?<br />
2. Or does it complicate it?<br />
3. Are there performance benefits of using ID attributes?<br />
87
Can you avoid using IDs or classes? In many, if not most, cases it’s very likely that you can! The<br />
rest of this tutorial will use this knowledge to show you how to effectively use these methods<br />
to select pretty much anything you want without creating an ID or CLASS infestation in your<br />
HTML code for every single element. But first...<br />
Get in the Habit of Using Context<br />
Thinking about context, or the confinement area of your selection is not always about speed,<br />
but rather, it’s about organizing your code and the way you think about CSS selectors. Let’s<br />
take a look at the following diagram, in which two similar DIV elements serve as the context<br />
of a selection.<br />
Notice that the contents of each of the two DIV blocks defined as possible contexts are arbitrary<br />
elements of any type. This is the “clean slate” mentality of an experienced <strong>jQuery</strong> developer.<br />
We want to avoid assigning IDs to most of them, unless you really are certain that it will<br />
make your elements easier to select.<br />
When it comes to choosing a selection within a context element, we need to think of assigning<br />
an ID to the context element. The diagram above is just a simple example. However, you will<br />
need to use the code from your real-life HTML page in order to determine what that context<br />
should be in the first place... that code may not look so simple at all. Especially this is true<br />
when you are working with someone else’s code and seeing it for the first time.<br />
You may think, well, what is the benefit of not using IDs everywhere? The benefit is mostly in<br />
the alternative way of thinking about your code. It has no other advantages whatsoever. But<br />
this alternative, “careful” way of thinking will determine your efficiency as a <strong>jQuery</strong> developer<br />
in the long run.<br />
Let’s take a look some of the ways in which this way of thinking can be helpful.<br />
88
Whose Children Are These?<br />
If we are to avoid using IDs completely, except when we need to assign them to a context, how<br />
do we navigate the DOM?<br />
We do so by using parents and children. But which elements are children of which parent<br />
elements? How does the DOM determine that? Just like in the real world, children belong to<br />
parents. But those parents can also be children of their parents, and so on. It’s just a matter of<br />
perspective. Let’s take a look at this diagram that explains relationships between parents and<br />
children:<br />
If each box on this diagram represents an HTML element, then the first child of the body tag is<br />
also the parent of all green children.<br />
The second child of the body tag is also the parent of all yellow children.<br />
Each individual yellow “child” is also an HTML element. Then black children 1, 2 and 3 are the<br />
children of one of the yellow child whose parent is the second child of body tag. Trivial stuff<br />
when you have a visual guide.<br />
Using :nth-child Selector<br />
Instead of using IDs for everything we will use the :nth-child selector that works on tag names<br />
Let’s assume that we have a DIV and that we have a few other elements stored inside it; in particular<br />
a DIV element, a SPAN element followed by 3 more DIV elements:<br />
89
The :nth-child(2) will select the span element. Index 2, in this case is the literal 2nd child. Indexing,<br />
in this case, does not begin with 0.<br />
A Small Detail About Using :nth-child Selector<br />
The <strong>jQuery</strong>’s implementation of nth-child selector is somewhat peculiar when dealing with<br />
children of different types in the same parent. If we take the diagram from above as an example<br />
and create a selector such as this one:<br />
$(“body div div:nth-child(2)”)<br />
It will not select anything at all. The second DIV child (whatever that may mean in this case?)<br />
simply doesn’t exist. Because the second child is an element of type SPAN, not DIV. Logically,<br />
you would think this selector would choose the DIV after the SPAN element. But that would<br />
be wrong, because that DIV element can be rightfully selected as div:nth-child(3).<br />
Had all of the elements been of type DIV, then this selector would actualy work.<br />
You can see now that this selector prioritizes the notion of child, not what type that child is...<br />
but that it is a child. It’s just how it works when different types of elements happen to be children<br />
of the parent element. This is not a bug.<br />
90
Next, let’s explore the possibility of making a selection using the first and last keywords.<br />
First and Last Children<br />
There are three different ways in which <strong>jQuery</strong> allows selecting HTML elements by first or last<br />
element in a container. Consider the following diagram:<br />
It doesn’t matter which way you choose. However, the colon character allows us to “glue” the<br />
selector to a particular element kind. The example above does not explicitly state what type of<br />
an element we are selecting. In order to do that, you would write something like div:last.<br />
If you are going to explicitly specify the type of an element you want to choose, such as DIV<br />
(not shown in the diagram) notice that there would be no space between div and the colon<br />
character.<br />
If there was a space between div and colon, however, it would mean a completely different<br />
thing. Remember that the space is a selector in its own right, it means “go inside the element”,<br />
so the selector such as div :last would seek the last child of an element located inside an arbitrary<br />
div block anywhere on the page - it would even select all children of any DIV element on<br />
the page.<br />
91
Selecting by “empty” Element<br />
We can also select elements that are empty as in nothing here. An empty element<br />
is an element that doesn’t contain any text or other elements within the two enclosing tags.<br />
In third example, even though there is clearly a value assigned to one of the input elements<br />
the :empty selector will still select both input elements. Why? Because is technically<br />
empty. It is not like . The :empty selector only works on a pair of tags. It checks the<br />
content between two tags, not the value attribute. (At least as of 1.7.1 version of <strong>jQuery</strong>.)<br />
Hidden or Visible<br />
This is self-explanatory. You can select an element that is hidden (has visibility:hidden) or an<br />
element that is visible by using the following selectors:<br />
$(‘:hidden’) // select all hidden elements<br />
$(‘:visible’) // select all visible elements<br />
Even or Odd<br />
One of the unique types of selectors <strong>jQuery</strong> offers are the :even and :odd selectors. You can use<br />
:even or :nth-child(even) interchangeably, they select absolutely the same things.<br />
92
<strong>jQuery</strong> Events<br />
Because <strong>jQuery</strong> is so simple to use, lots of times people don’t even want to understand what<br />
events are. As long as they can just use the functions with short names like click() or css().<br />
If you don’t understand what events are, now is the time to learn. If you are pursuing an interest<br />
in <strong>jQuery</strong>, you are likely to end up learning other programming languages as well. Those<br />
languages may use events, and even the same concepts such as event bubbling. I will get to<br />
event bubbling later in this tutorial, but for now let’s see how events can be triggered.<br />
Let’s not overlook the nature of events in general. <strong>jQuery</strong> provides us with an interface to existing<br />
Javascript events. All events that there is a <strong>jQuery</strong> function for, are actually tied to some<br />
Javascript event.<br />
Javascript event functionality is hardwired into the browser’s implementation of Javascript in<br />
that browser. Most events are assigned to empty functions from the start. We can extend the<br />
functionality of an event, by overriding that function with our own. So then, the most important<br />
thing about events, is that we know what their names are and what they do.<br />
Learning what events are available to us is something that comes with the experience of writing<br />
Javascript code, but I also included a table of all <strong>jQuery</strong> events in the last section of this<br />
tutorial. For now, let’s take a look at one of the most basic examples, where an event is attached<br />
to the main window object.<br />
Consider the following <strong>jQuery</strong> selector and event handler function:<br />
$(window).load( function(){ alert(‘Window finished loading.’); } );<br />
I highlighted the handler function in yellow. This is also known as an anonymous function<br />
because this function doesn’t have a name. By using an anonymous (or nameless) function, we<br />
simply want the code to be executed as soon as we define it within the same statement. We are<br />
not concerned with that function’s name. That is why we omit it. This function is the code you<br />
want to be executed when a <strong>jQuery</strong> event occurs. In this case we have chosen the load event,<br />
which is the equivalent of the window.onload event, as shown below:<br />
<br />
<br />
window.onload = function() { alert(‘Window finished loading.’); }<br />
<br />
<br />
Can we use the code above instead? Yes, we can even use the old-school onload = “” in the<br />
body tag in the HTML of the webpage.<br />
93
Either way, exactly the same event will be triggered. But this is a simple example. Sometimes<br />
some events require different syntax, based on which browser you are writing your Javascript<br />
code for. <strong>jQuery</strong> saves us from thinking about those details.<br />
<strong>jQuery</strong> just makes using events more convenient for the developer. Most of the time <strong>jQuery</strong><br />
events are expected to work exactly the same in all browsers with just a few exceptions, for example<br />
the events related to capturing keyboard key strokes may not produce the same results<br />
in some versions of Internet Explorer.<br />
Two ways of attaching an event handler to an event.<br />
<strong>jQuery</strong> offers us with two ways of attaching event handlers to Javascript events.<br />
One way is by using the bind(event, handler) function, in which you are required to specify<br />
the name of the event you want to target, and the handler function, which will run when that<br />
event is fired.<br />
The other way is to use the function designed to handle a specific event.<br />
Also remember that <strong>jQuery</strong> events operate on <strong>jQuery</strong> selections made prior to attaching the<br />
event function to them. Here is an example of the first method, using the bind() function:<br />
$(window).bind( “load”,<br />
function()<br />
{<br />
alert(‘Window finished loading.’);<br />
});<br />
And here is the equivalent using the second, a more direct method:<br />
$(window).load( function() { alert(‘Window finished loading.’); } );<br />
Will you use bind or call the load function directly? The choice is yours. It really makes no difference.<br />
How to Unbind an Event<br />
The title of this section should have probably read: Why should we unbind events?<br />
Whenever you bind an event handler to an event, you tell the processor to allocate memory for<br />
it. The more event handlers you have running at the same time, the more memory you are using.<br />
This is why it’s important to unbind or detach your event handlers soon as you no longer<br />
need them.<br />
94
Of course, the effects of binding a few event handlers are invisible in short script programs, the<br />
practice of unbinding events becomes more important when dealing with large web applications.<br />
But it’s still a good habit to have.<br />
In order to unbind an event you call the function called unbind():<br />
$(window).unbind(“load”);<br />
The code above will unbind the “onload” handler from window that we attached previously,<br />
whether it was attached using the bind function or the load function. Of course, in this particular<br />
case, this is a faulty example. Javascript probably already unbinds the event handler of<br />
onload event internally, because it can only fire once. So they unbind it once it has played out.<br />
But this is just an example. Most events will not be unbound automatically. That’s programmer’s<br />
responsibility.<br />
Sometimes, you will only want to bind an event once, and remove it once it has played out.<br />
There is another <strong>jQuery</strong> function that fits this discussion. It is called one(). This function binds<br />
an event handler to an event, and unbinds it soon as it is finished executing. In other words,<br />
consequent events will not be triggered.<br />
Let’s attach the click event to an arbitrary HTML element with ID “orange”:<br />
$(“#orange”).one(“click”, function() {<br />
alert(“This will be displayed only once.”);<br />
});<br />
The code above is the exact equivalent of the following:<br />
$(“#orange”).bind(“click”, function( event ) {<br />
alert(“This will be displayed only once.”);<br />
$(this).unbind( event );<br />
});<br />
Applications can get complex, and there are many ways to bind and unbind event handlers to<br />
events. So, what is the smartest way of binding and unbinding? It depends.<br />
If you are using only your own script, and are not planning on using any outside libraries, all<br />
that we have just discussed will suffice.<br />
But how to write code carefully, in a way that doesn’t clash with what other scripts may be doing<br />
to the same elements we are?<br />
95
There is, indeed, a third way to bind and unbind event handlers. An example can be seen below:<br />
var handler = function()<br />
{<br />
alert(‘The quick brown fox jumps over the lazy dog.’);<br />
};<br />
$(‘#orange’).bind(‘click’, handler);<br />
$(‘#orange’).unbind(‘click’, handler);<br />
By naming our event handler (so that it is no longer a function closure) and separating it from<br />
the bind and unbind functions, we are able to explicitly tell <strong>jQuery</strong> to work with the original<br />
location in memory of the object that we created.<br />
This means that you will be binding and unbinding only click events assigned by your script.<br />
Imagine if some other script (not developed by you) assigns a click event handler to the<br />
HTML element with ID “orange” and that we unbind it by accident using our code. We would<br />
interrupt the flow of that other script.<br />
But Javascript code can be very sensitive to syntax being used. There is one more precaution<br />
you should be aware of when binding and unbinding your event handlers. Consider the code<br />
below:<br />
$(‘#orange’).bind(‘click’, function()<br />
{<br />
alert(‘The quick brown fox jumps over the lazy dog.’);<br />
});<br />
// This will NOT unbind the event handler attached above<br />
$(‘#orange’).unbind(‘click’, function() {<br />
alert(‘The quick brown fox jumps over the lazy dog.’);<br />
});<br />
The unbind event in the example above will not actually unbind the event handler attached<br />
with the bind function right above it. Why not? Because the first function created a function<br />
closure located at an arbitrary address in memory.<br />
The second function did the same thing. Essentially, we are telling Javascript to unbind an<br />
event handler we have just created, yet, instead of giving the unbind function the handle to<br />
that event, in the second example we are trying to unbind a brand new function we are creating<br />
at the same time.<br />
Nameless functions that we have specified “on the fly” will always be stored at a new, unique<br />
address in memory even if their contents are exactly the same.<br />
96
Using toggle() Events<br />
Toggling between two values or two different CSS element styles is not supported natively by<br />
Javascript. There isn’t a “toggle” event. <strong>jQuery</strong> makes this possible by adding its own toggle<br />
event that will actually use Javascript’s native “onclick” events.<br />
The event handlers attached to a selection with the toggle() function will be triggered on a<br />
mouse click event. Think of toggle() as an advanced click event that can do more than one action,<br />
based on how many event handlers are passed to this function.<br />
<br />
$(document).ready(function()<br />
{<br />
$(“body”).toggle(<br />
);<br />
});<br />
<br />
// Do this the first time selected element is clicked:<br />
function() { $(this).css(‘background’, ‘#ff0000’); },<br />
// Do this the second time selected element is clicked<br />
function() { $(this).css(‘background’, ‘#0000ff’); },<br />
// Do this the third time selected element is clicked:<br />
function() { $(this).css(‘background’, ‘#ffffff’); }<br />
// etc.. and then start over with the first event handler again<br />
Pass as many event handlers to the toggle function as the states you want to be toggled on<br />
mouse click. Most of the time this function will be used with just two event handlers for “on”<br />
and “off ” state. The example above uses 3. Every time you click on the “body” of your page, it<br />
will change colors, first to red, then to blue, and then finally back to white. Click a fourth time,<br />
and the process starts all over again with triggering the first event handler again.<br />
What is Event Capture and Event Bubbling?<br />
Without understanding the DOM, you can’t understand event capture and event bubbling. In<br />
one of the previous newsletter episodes I explained the DOM using a simple diagram. It’s basically<br />
a tree of elements. Children are attached to their respective parent elements. And there<br />
can be more than one child attached to the parent. Children can also be parents of their children,<br />
and so forth.<br />
The DOM has two ways of detecting events. One from the top down and the other from the<br />
bottom up. The first method is known as event capture, the second is called event bubbling.<br />
97
Event Capture<br />
Even though the image was clicked, the image element is not the first to actually receive the<br />
first event. Instead, the event is first processed by the document. In other words, the document<br />
captures the event first. It then passes it to first div element, then to the second, and finally the<br />
event arrives at its target, which is the image element. Each of the “ancestor” elements of the<br />
target (img) receive the event and pass it on until the target element is reached. The target element<br />
is defined by the original element that receives action first.<br />
Event Bubbling<br />
Bubbling is the reverse of capture. In this case, the target element that receives the action, such<br />
as a mouse click, will process the event first using its event handler. Then, the event “bubbles”<br />
up the DOM ancestor tree, all the way to document. Sort of like the bubbles in a glass of champagne.<br />
Both event capture and bubbling happen behind the scenes, and many developers are not<br />
aware that this is even happening while working with <strong>jQuery</strong> event functions. But this knowledge<br />
is important because it is often the source of confusion when it comes to writing complex<br />
script programs.<br />
List of All <strong>jQuery</strong> Events<br />
Your productivity as a <strong>jQuery</strong> developer will depend on how many event names you can recall<br />
from your memory. The more events you commit to your memory, the less time you will<br />
spend looking them up. Below is a table containing some of the <strong>jQuery</strong> events. You can see a<br />
list of all <strong>jQuery</strong> events by going to the link below the table. I just didn’t want to clutter this email.<br />
The link redirects to a page that can be printed out for your reference.<br />
Event function Event description<br />
.bind()<br />
.blur()<br />
.change()<br />
.click()<br />
.dblclick()<br />
.delegate()<br />
.die()<br />
.error()<br />
.focus()<br />
.focusin()<br />
.focusout()<br />
.hover()<br />
.on() and off()<br />
Attach a function to an arbitrary event of your choice.<br />
Attach “focus left a selected element” event.<br />
Value of the selected input element has changed.<br />
The selected element(s) has been clicked.<br />
The selected element(s) has been double clicked.<br />
Old function for .on(), use. on() instead.<br />
Remove all events that were attached with .live()<br />
Bind a handler to the “error” Javascript event<br />
The selected element(s) received cursor focus<br />
Detect focus of an input element nested inside an arbitrary parent (the selection)<br />
Detect the loss of cursor focus of an input element nested inside a parent.<br />
Mouse enters the area of an element.<br />
New function equivalents to use instead of .bind() and .unbind()<br />
For the full list of <strong>jQuery</strong> events refer to this page:<br />
www.authenticsociety.com/jquery/list-all-jquery-events.html<br />
98
Speed Up Your <strong>jQuery</strong> Code<br />
<strong>jQuery</strong> is a great library for writing interactive web applications. It has a large feature set, it’s<br />
extremely easy to use compared to the plain Javascript code and it is cross-browser compatible.<br />
Write code once and it will work in all browsers just the same. Well, 99% (most of the time).<br />
As you learn more about <strong>jQuery</strong>, you will start writing more complex CSS selectors and you<br />
will discover more advanced functionality. But if you are not attentive enough when using<br />
<strong>jQuery</strong>, chances are you will be writing inefficient code.<br />
When I learned my first computer language, C++, I also learned that you could write a program<br />
using pointers (references to an address in memory) that could literally crash your computer.<br />
As a C++ programmer, it was your responsibility not to access memory you shouldn’t<br />
have.<br />
A similar type of responsibility exists when writing <strong>jQuery</strong> code, but not many web developers<br />
are aware of it. Misusing <strong>jQuery</strong> selectors in combination with literally “selecting too many<br />
things”, can cause a major slowdown in processing speed of your queries.<br />
<strong>jQuery</strong> selectors can’t crash your computer. But they can possibly freeze your browser. This is<br />
mostly true when it comes to CSS selectors. The versatility and easiness with which you can<br />
access the DOM, you could be selecting too many things you don’t need to, without knowing<br />
it. By doing that you can overwhelm the system resources of your browser and slow down the<br />
functionality of your site.<br />
The <strong>jQuery</strong> development team were aware of this situation. Therefore, they invented a solution<br />
to this potential problem. They called it context.<br />
But before we get there, let’s consider the general rules when writing high performance code<br />
using Javascript.<br />
The first rule of Javascript Performance<br />
All Javascript frameworks can only be as fast as the native Javascript implementation.<br />
That’s up to the people who developed the browser you are using and the processing speed of<br />
your computer. But this also means that no matter how clever your <strong>jQuery</strong> selector code is,<br />
there is a very realistic chance that you are not going to outdo limits set by the developers of<br />
Javascript as part of your browser’s implementation.<br />
99
When selecting elements, and as far as performance of Javascript goes, the best you can do is<br />
to use the two utility functions getElementById() and getElementsByTagName(). And as you<br />
may know, DOM manipulation is computationally expensive.<br />
It’s important that we minimize the number of DOM requests. Working with 5-10 nodes will<br />
probably not make a big difference. But what if you are looking to select a lot of things? By a<br />
lot, I mean 1000? Or 5000? It’s not unreasonable for more advanced applications to select a<br />
large number of elements. How does this apply to <strong>jQuery</strong>?<br />
<strong>jQuery</strong> has a plentitude of ways in which you can select elements. We already went over a decent<br />
number of selectors and the things you can do with them in the previous tutorial. The act<br />
of selecting multiple elements is not without consequences. Don’t be fooled by the simplicity<br />
of <strong>jQuery</strong> selector syntax. This is where context begins to play an important role.<br />
Let’s take a closer look at the $() function offered by <strong>jQuery</strong>. Remember that you can use the<br />
dollar sign and the keyword <strong>jQuery</strong> interchangeably.<br />
<strong>jQuery</strong>( selector, [context] )<br />
As you can see, <strong>jQuery</strong> actually takes two parameters. The second one, indicated by square<br />
brackets [ and ] is the context, and it’s optional. That is why so many people tend to be unaware<br />
of its existence.<br />
We already know enough about the selector parameter. It’s a set of elements intermixed with<br />
helper characters (such as the space, a comma, brackets or an arrow) that tells <strong>jQuery</strong> what<br />
you want to select.<br />
You can use the nth-child keyword to select a specific element by its index location in the<br />
DOM node. You can select elements based on whether they are visible or not, by their class, by<br />
id and by their type. You can go crazy because combinations abound. Some complex combinations<br />
can also slow you down when you are walking wearing a pair of your <strong>jQuery</strong> selector<br />
shoes. The selector argument is your left shoe. The context is your right shoe. Let’s see how we<br />
can use these shoes to outdance any amateur <strong>jQuery</strong> developer.<br />
Our first rule of Javascript performance states that frameworks can only be as fast as the native<br />
Javascript implementation in your browser. This means that our fastest selector for a single element<br />
must be using getElementById(). It needs to only find one element of your choice in the<br />
DOM. It must then stop its search, without having to look for anything else. In addition, you<br />
can use getElementsByTagName(). This function will result in a collection of elements based<br />
on their tag name like DIV, SPAN or TABLE, etc.<br />
100
Let’s now look at the <strong>jQuery</strong> way of doing these things:<br />
$(‘#clockwork’) // will use getElementById()<br />
$(‘div’) // will use getElementsByTagName()<br />
A thinking man is now confronted by this logic: If we are to use <strong>jQuery</strong> we must stick only to<br />
these two ways of using selectors. But this will surely defy the very purpose of why that man<br />
decided to use <strong>jQuery</strong> in the first place?<br />
Having thought this, what do we now do in order to write high performance code using the<br />
flexibility of <strong>jQuery</strong> selector variations that stretch beyond the two examples? We do this by<br />
providing the context.<br />
The second rule of Javascript Performance<br />
By laser-targeting the area which we want to operate on, by defining the confinement of, and<br />
making specific the DOM block we will be working with, and by eliminating all the other garbage<br />
we don’t need to include as part of our selection, we increase performance of our <strong>jQuery</strong><br />
code.<br />
Like a horde of provoked hounds, by default <strong>jQuery</strong> selectors will start their search from the<br />
very top of the DOM tree, and propagate down all branches. We can exclude some of these<br />
branches from the search algorithm entirely. By searching less space, we find what we are looking<br />
for faster. This way the browser will do less work and your program will execute faster. The<br />
hounds have less distance to travel.<br />
The second argument of the <strong>jQuery</strong> function, immediately after the selector parameter is the<br />
context argument. It’s a means to choose the branch of DOM you want to work with, ignoring<br />
all other branches in the tree of HTML elements.<br />
The default the context is the Document. The whole DOM tree. That’s what we search if we<br />
skip the context parameter. This can be a lot of markup to select, that we don’t really need to.<br />
But when we pass in a reference or another $() selector, we can reduce this area significantly.<br />
All of a sudden, context becomes our best friend, and not the scary, enigmatic entity you never<br />
wanted to learn about.<br />
Choosing the Right Context<br />
Context is incredibly useful. We now know this. But before you go and start using it in your<br />
own website, consider that misusing context can lead to negative results. In order to demonstrate<br />
this, we will consider the following example.<br />
101
Let’s say that we have a form residing in an element whose class name is .clockwork. And we<br />
want to select all input elements that happen to be using class .orange within that form.<br />
<br />
<br />
<br />
<br />
<br />
<br />
Using the .orange handle is just another way of referring to an input box. Let’s take a look at<br />
how we would do this without using context first. This selector will select all visible input elements<br />
anywhere in the DOM.<br />
And with context?<br />
$(‘.orange:visible’)<br />
$(‘.orange:visible’, $(‘.clockwork form’))<br />
But this would be a step backward. We just doubled the amount of work for <strong>jQuery</strong> by using<br />
two complex selectors, not just one.<br />
Remember our first rule of Javascript performance? Since we already know that using $(‘#id_<br />
name’) is the absolute fastest way to perform a DOM selection, we will use that knowledge to<br />
our advantage. You should always aim to simplify your selectors in such a way if you’re looking<br />
for a performance advantage.<br />
Instead, let’s rewrite the example from above to make it fast:<br />
$(‘.orange:visible’, $(‘#my_form’))<br />
Now this will cut the performance bottleneck of your <strong>jQuery</strong> selectors. The more expensive<br />
selector .orange:visible now works within the confines of a less expensive selector #my_form.<br />
In fact, this is the fastest selector you can possibly get with <strong>jQuery</strong>.<br />
Remember the general rule when speeding up the performance of your <strong>jQuery</strong> selectors:<br />
Confine a complex selector to a less complex context.<br />
102
Practical <strong>jQuery</strong> Lessons<br />
Instead of talking about something specific, I decided to do something new. In this section we<br />
will take a bird’s eye view of <strong>jQuery</strong> functionality by briefly going over a number of different<br />
functions and circumstances in which they are used.<br />
Sometimes it is possible to become confused about how things work. Or rather, why they don’t<br />
work as we believe they should. The answer to such questions usually lies in understanding<br />
multiple languages such as JavaScript and CSS. Throughout the lessons I will try to capture<br />
these details that I hope will shine more light on the kind of tools <strong>jQuery</strong> offers to us. But also<br />
on the proper way to think about the syntax.<br />
These lessons are designed to display the versatility of <strong>jQuery</strong> and how with just little code we<br />
can gain more control over our JavaScript program. So, let’s begin.<br />
Lesson 1: The :not Selector.<br />
As we learned in the beginning chapters, in large part <strong>jQuery</strong> programming is about understanding<br />
CSS selectors. It’s common to use # (the number symbol) and . (the dot) as part of<br />
our selectors because it’s natural to select things we know are there like classes and ids.<br />
However, certain cases demand we select everything except a certain type of an element. The<br />
little known :not selector can help you accomplish that. Consider the following example where<br />
we <strong>hide</strong> all paragraph elements on the screen except those within an unordered list (ul):<br />
$(“p:not(ul p)”).<strong>hide</strong>();<br />
As you may know, the p selector means select all paragraphs. Note that there is no space between<br />
p and :not. Had there been a space, the selector would not work. That’s a completely different<br />
context. A new selector ul p is specified after :not within a new set of parentheses. This<br />
statement can be read as select everything except paragraphs inside the ul tag.<br />
Remember that when working with <strong>jQuery</strong> we are also working with JavaScript and CSS. At<br />
the same time. This means that the rules laid out by CSS still apply. And this is important to<br />
understand because part of understanding selectors depends on your understanding of CSS,<br />
and not <strong>jQuery</strong> itself.<br />
When working with <strong>jQuery</strong>, little things matter. For example, a space between p and :not<br />
would no longer produce the same results. This is because the space character is a CSS command<br />
that tells CSS to select a completely new set of elements seen after the previous selector.<br />
This is after all, CSS. Remember that the C stands for Cascading? This means we need to keep<br />
in mind that HTML elements are nested inside other elements. And that’s natural.<br />
103
Luckily, this book is called <strong>Understanding</strong> <strong>jQuery</strong>. So, below we will explore the hidden logic<br />
behind some selector combinations and why they do not seem to work as our intuition suggests<br />
that they should. Breaking this down like that will help us understand the deeper concepts<br />
behind CSS selectors logic when using them in combination with <strong>jQuery</strong>.<br />
Even though <strong>jQuery</strong> makes programming easy some details must not be overlooked.<br />
It appears as though the :not selector requires a base selector such as body. However, it will not<br />
work if the base selector is the star selector (*) which selects everything unless the CSS style<br />
for * is explicitly specified by the programmer before calling the <strong>jQuery</strong> code. I don’t know<br />
whether the developers of <strong>jQuery</strong> inteded it to be this way, but strangely, the following examples<br />
will not produce intended results:<br />
$(“:not(p)”).<strong>hide</strong>(); $(“* :not(p)”).<strong>hide</strong>();<br />
Both examples will select and <strong>hide</strong> everything. Hmm, that can’t be right. Because clearly it<br />
seems that the :not selector is used intuitively and it says select everything except p.<br />
Is this intended functionality or an error in <strong>jQuery</strong> library? Keep in mind that the :not selector<br />
is ignored in both of these cases - the asterisk is assumed in both. I would have loved to be able<br />
to “select everything but” using the star/asterisk (*) selector in combination with :not. But there<br />
are rules.<br />
It’s easy to think that the above examples should just work. That’s intuitive thinking. But these<br />
selector do not seem to match what we believe they should. However, this can be explained by<br />
the cascading nature of CSS in combination with the hidden asterisk. Let’s take a look here:<br />
$(“:not(p)”).<strong>hide</strong>();<br />
The reason this selector will not select everything but the paragraphs is because that is not<br />
what it actually selects! (Or doesn’t select). Remember, that all paragraphs on your page are<br />
also within other tags. That is the knowledge we needed. When we select “:not(p)” what actually<br />
happens is the entire DOM is selected and hidden (that means everything on the page)<br />
because a CSS selector will select everything above in a cascading fashion of things. And the<br />
reason for this is that the asterisk is assumed even when we do not explicitly specify it.<br />
Now, let’s think about this. If we just selected the entire DOM and said “<strong>hide</strong> it” with <strong>hide</strong>(),<br />
that means everything within the html, body tags, etc. Even the paragraph tags will be hidden.<br />
Even though we just specified not to <strong>hide</strong> them. What we are hiding is actually the entire<br />
DOM element which makes the entire page disappear.<br />
104
There is a solution to this problem. And the solution is, again, to explicitly specify body as part<br />
of the selector. Let’s take a look at the proper way of using the :not selector:<br />
A single space character.<br />
$(“body :not(p)”).<strong>hide</strong>();<br />
Notice I added body followed by a space. Now, this will produce a correct result. But why?<br />
Referring to our earlier discussion about selectors in the book we learned that only the last<br />
element in the hierarchy specified using the space character will be selected.<br />
But we can’t simply add a space character without a preceding HTML element. So we explicitly<br />
specify the body tag too (by default <strong>jQuery</strong> sees lack of any preceding element as if the asterisk<br />
was used). In this example the body tag itself is not selected, only the :not(p) elements.<br />
This means that when I added the body tag and the space that followed, it is the space that is<br />
explicitly telling the selector: do not select body … only select what is after the space character.<br />
This small but important modification to the selector solved the problem. The selector will<br />
now do exactly what is being asked. When working with :not selector it is important to make<br />
explicit definitions like this and specify exactly what you are looking to select, rather than<br />
making a quick guess and hope it works.<br />
Using the :not Selector with the Asterisk<br />
We know that the star selector, also known as the asterisk selector (*) is used to select everything<br />
in the DOM structure. This means the doctype, html, head, title, body, etc. In other<br />
words, everything, even tags outside the body tag. They are all part of the DOM.<br />
$(“* :not(p)”).<strong>hide</strong>();<br />
Only last element in the<br />
hierarchy will be selected.<br />
Here we will face exactly the same problem as we did in the previous example where we used<br />
the body tag. However, this time we are selecting the entire DOM with the asterisk. Again, the<br />
selector in the example above will not work as intended. We are indeed selecting everything<br />
and then hiding it but only then asking not to <strong>hide</strong> paragraphs.<br />
In the previous example our solution was to simply explicitly state that we want to <strong>hide</strong> everything<br />
except the paragraphis within the body tag. That solved the problem and made the selector<br />
behave correctly. But the asterisk selector is different because it is the default selector.<br />
105
he asterisk selector (*) is the default behavior of any CSS selector whether it is specified or not.<br />
In other words, an identical solution could look something like this:<br />
$(“* body :not(p)”).<strong>hide</strong>();<br />
Again, being explicit in telling <strong>jQuery</strong> exactly what we want to select fixed the problem. You<br />
can see the true hierarchy forming. First the asterisk, then body, then everything else.<br />
So, even though only :not(p) is the true defining point of what is being selected, you can see<br />
how using the understanding of the DOM hierarchy itself also plays a big role in selecting elements.<br />
If you find that your selector isn’t working for some reason, check its hierarchy integrity.<br />
The best bet is to always be as specific as possible.<br />
Looks like we’ve come around a full circle. We started this lesson with saying that the selectors<br />
$(“* :not(p)”) and $(“:not(p)”) do not produce a result that at first they seem they should.<br />
We then learned that in order to solve the problem we should explicitly indicate the context<br />
whether it was the asterisk selector, the body tag, or both.<br />
It should be easy to see now that $(“* :not(p)”) and $(“:not(p)”) are one and the same thing<br />
exactly. There is absolutely no difference between the two selectors and the second one assumes<br />
the asterisk by default anyway.<br />
A Quick Note About Explicit Default CSS Definitions<br />
While doing research about the inner workings of CSS selectors in the context of <strong>jQuery</strong> I<br />
noticed something rather interesting. Even a selector such as $(“* :not(p)”).<strong>hide</strong>(); that we<br />
just discussed above would not work quite the same under certain conditions. What are these<br />
conditions?<br />
First we must understand that the asterisk is not the same as body. The asterisk assumes absolutely<br />
everything. Even the tag. And that’s the key to understanding why some CSS<br />
selector may seem like they do not work in some instances. Remember that the tag<br />
itself can contain CSS styles. If it does, it will certainly affect the tag as well.<br />
To fix this problem we should stick to one simple rule. If you ever wish to use the asterisk<br />
selector, you must always specify the default CSS style for everything using the asterisk command<br />
within the default style.css file. As in: * { background: white; } Doing this will reset the<br />
global style for every single tag on the page. If you don’t do this you will find that the asterisk<br />
selector may not behave as intended. So the two core principles working with * and body selectors<br />
are to always provide a default CSS style and be explicit with your CSS selectors.<br />
106
<strong>jQuery</strong> provides a secondary way of dealing with not-based selections. And that is the direct<br />
.not() method executed on a selection. Let’s take a look:<br />
$(“* body p“).not(“ul”).<strong>hide</strong>();<br />
But in this case, the .not method is used as a post-production filter, rather than a direct part<br />
of hierarchy. In other words, what we don’t need is “added” last using the .not method. A little<br />
different from how the inline :not selector works. So the above example is saying: select all<br />
paragraphs tags in body, but not those within ul (unordered list) elements.<br />
Which one is better :not or .not()? You will have to decide based on the circumstances. In<br />
some cases one is easier to use than the other. The DOM hierarchy has unlimited capacity for<br />
different element nesting scenarios.<br />
However, if you are dealing with a large number of elements you wish to skip, keep in mind<br />
that in many cases the inline :not achieves a faster performance than the equivalent .not()<br />
method.<br />
Lesson 2: Storing Data Inside HTML Elements<br />
We use <strong>jQuery</strong> to work with HTML elements. Sometimes it is desired to attach arbitrary data<br />
to an element beyond the default attributes like id, class, href, src, and so forth. What if we<br />
wanted to add our own custom attributes to the element? In <strong>jQuery</strong> the .data() method takes<br />
care of the problem. Let’s say we have this DIV element:<br />
Description of my cat.<br />
In order to attach arbitrary data and relate it to this element we can use the following method:<br />
$(“#mypet”).data(“cat”, { legs: 4, eyes: 2, color: “orange” });<br />
Notice that the data in this case is a JSON. But it could be any variable, even a function. Remember,<br />
everything in JavaScript is an object. The value of “cat” is an object. That means it can<br />
be anything. Now we can retreive the data from this element using the data method again:<br />
var data = $(“#mypet”).data(“cat”);<br />
var legs = data.legs;<br />
var eyes = data.eyes;<br />
var color = data.color;<br />
107
It’s interesting to note that the data() method creates an actual attribute and attaches it to the<br />
element. We know that it is theoretically possible to assign a custom attribute to any HTML<br />
element:<br />
<br />
Even though this will work, it will not validate. The proper way of doing that would be to prepend<br />
the data-* prefix to the beginning of the attribute name. Let’s try again:<br />
<br />
<strong>jQuery</strong> is already aware of this and it will automatically prepend data-* prefix to each new attribute<br />
created using the data() method. Let’s take a look at the following example:<br />
$(“#another_pet”).data(“wings”, { feathers: 1000 });<br />
This code will create an attribute called data-wings, not wings. The data() method <strong>hide</strong>s all of<br />
that from us, even though that is what happens physically inside the element. The data method<br />
in this example will also assign the JSON containing variable feathers, which equals 1000.<br />
We already know that we can use the data() method again to retreive the object back and store<br />
it in a variable. But you can also access this data by calling the attr(“data-wings“) method.<br />
$(“#another_pet”).attr(“data-wings”);<br />
This is just for reference. You should always use the data() method to retreive the values set using<br />
the data() method.<br />
Storing data inside HTML tags is a helpful technique for developing User Interfaces and other<br />
dynamic applications. Imagine that we created custom attributes and attached them to an<br />
HTML element that represents a User Interface window that does some function and needs to<br />
retain its current state even after being moved to a new HTML element within. the website.<br />
Now imagine that we want to copy and paste that window and integrate it into part of our<br />
website without having to keep track of the variables and the current state of that window in<br />
the global scope of our JavaScript application. Why not simply grab the entire element along<br />
with the custom attributes it contains?<br />
Simply use <strong>jQuery</strong>’s html() method to grab the window and again paste it into the new location<br />
using the same method. You get the idea, the entire HTML element is moved from one location<br />
into some place holder on the site retaining all attributes containing some type of data.<br />
108
Lesson 3: Callback Functions<br />
All <strong>jQuery</strong> statements eventually finish execution. Let’s say we selected some elements and we<br />
ran a function on this selection such as .css(), .<strong>hide</strong>(), .attr(), etc. In event-based web development<br />
it’s common to trigger a new event upon completion of some action. <strong>jQuery</strong> developers<br />
knew this and gave us a way to call a custom function when an action is completed.<br />
Most <strong>jQuery</strong> methods provide a special parameter where such function can be specified. This<br />
function is often left nameless, because we are not interested in storing it for future use. We are<br />
only interested in using it once every time a method or an event is executed.<br />
Let’s attach a nameless callback function to a <strong>jQuery</strong> method css, which changes the font color<br />
of selected element(s):<br />
$(“div”).css(“color”, “red”, function() {<br />
alert(“the font has been changed.“);<br />
});<br />
The nameless function will fire soon as all div elements finished changing font color to red.<br />
Nameless functions are usually defined as the second or third parameter of a given <strong>jQuery</strong><br />
method. In some cases, the nameless callback function is the only argument of a <strong>jQuery</strong> method<br />
as seen in the example below where we use the .click() method to execute an event.<br />
$(“div”).click( function(){ /* execute code here */ } );<br />
A callback function is often passed to a <strong>jQuery</strong> method as the only or the last argument.<br />
Lesson 4: Using append and prepend methods<br />
The append and prepend methods help us attach HTML content around existing content.<br />
Consider the following examples. Let’s start with an empty div element and append new content<br />
to it using these two functions:<br />
$(“div”) .append(“New”); .prepend(“1”); .append(“2”);<br />
New 1New 1New2<br />
We start with an empty div and continue using the append and prepend methods to add new<br />
values around the original value. You don’t need to call call each function from a statement on<br />
a separate line. You can use the dot operator to chain all methods together as seen below:<br />
$(“div”).append(“New”).prepend(“1”).append(“2”);<br />
109
Let’s take a look at another practical example using prepend. This time let’s prepend paragraph<br />
with id p2 to the paragraph with id p1 using a <strong>jQuery</strong> selector instead of a string literal:<br />
Let’s run $(“#p1“).prepend($(“#p2“)) on the original HTML:<br />
Original HTML<br />
paragraph 1<br />
paragraph 2<br />
paragraph 3<br />
Result<br />
paragraph 2paragraph 1<br />
paragraph 3<br />
After $(“#p1”).prepend($(“#p2”)) is executed notice how the second paragraph was prepended<br />
into the first paragraph. But something else is even more interesting at work here. The paragraph<br />
that was prepended is gone from the original location. The functionality of the functions<br />
append and prepend is similar to the copy and paste effect. The element being prepended is<br />
removed from the original location.<br />
Lesson 5: Using appendTo and prependTo methods<br />
In the previous lesson we discussed append and prepend methods. Let’s now compare them to<br />
their near-equivalent methods appendTo and prependTo. These methods do exactly the same<br />
thing that append and prepend do. Except in reverse order as far as the syntax goes:<br />
$(“#p1”).prepend($(“#p2”)) ;<br />
$((“#p2”)).prependTo($(“#p1”));<br />
The two statements above produce exactly the same result as shown in the second diagram<br />
from the Lesson 4. The only difference is in the syntax and parameter reversal. There are cases<br />
when either syntax makes it easier to understand the logic of your program.<br />
In Lesson 4 the first example dealt with arguments passed as string literals. In other words, we<br />
were prepending plain text within and to an existing HTML element. As you can see, it is also<br />
possible to pass a <strong>jQuery</strong> object - which is what the $(“#p1”) selector returns - as arguments to<br />
append and prepend methods. But this isn’t unique to these methods alone.<br />
Most <strong>jQuery</strong> methods can accept the following as arguments:<br />
1. The string literal, like “text123”,<br />
2. The <strong>jQuery</strong> selector itself, like $(“p”), or<br />
3. The raw JavaScript DOM object like document.getElementById(“p1”).<br />
110
For example, the following statements do exactly the same thing. Pay attention to the type of<br />
values being passed as arguments to the prepend function. As you can see, the same function<br />
takes a multitude of different types of parameters.<br />
// First let’s define some variables<br />
var p1 = $(“#p1”);<br />
var p2 = $(“#p2”);<br />
// Now, all of the following will do exactly the same thing<br />
$(“#p1”).prepend( $(“#p2”) ); // using one string literal and one selector<br />
$(“#p1”).prepend(“#p2”); // using string literals<br />
$(p1).prepend(p2); // using variables<br />
$($(“#p1”)).prepend($(“#p2”)); // using selectors themselves as arguments<br />
// Using the raw JavaScript DOM reference to the object:<br />
$(document.getElementById(“p1”)).prepend(document.getElementById(“p2”));<br />
Internally, document.getElementById is what a <strong>jQuery</strong> selector like $(“#p1”) will use anyway.<br />
But the point is that you still can pass the object in any of these ways if you need to, if your<br />
program requires it or if it is just more convenient than any other way.<br />
Why do we need all these different ways? Sometimes the DOM is already available to work<br />
with and we don’t really need to use a CSS selector to find it. Other times the only way to get<br />
an object of an element in particular is to select it. If you already have a DOM handle (or a<br />
variable) to an element, you don’t need to use a CSS selector which will return a <strong>jQuery</strong> object<br />
to that element. Simply pass the DOM object to the <strong>jQuery</strong> method.<br />
Because <strong>jQuery</strong> methods are designed to work with different representations of the same<br />
HTML elements they make it so much more convenient to write JavaScript code.<br />
111
Regular Expressions<br />
How will you know it’s them when you see them?<br />
Regular expressions are common features in computer<br />
languages and text editors. Learning how to use them will<br />
increase your performance as a computer programmer and<br />
problem solver. JavaScript was designed with regex in mind.<br />
The phrase Regular Expression can be shortened. Regular expressions are commonly referred<br />
to as regex, or regexp in conversation. We use regular expressions to find or match a character<br />
pattern within a word or a line of text. For example, we can search for the word clock in the<br />
word clockwork. We can also find the words lock and work in the same word.<br />
lock<br />
clockwork<br />
Regular expressions helps us find words or character patterns inside text and then store the<br />
results in an array for further manipulation or modification. Another important function of<br />
regular expressions lies in their ability to count the number of times a pattern repeats inside a<br />
word or a sentence. For example, there are two o’s in the word clockwork. The following regular<br />
experssion example demonstrates how we can find and count all o’s in the word clockwork:<br />
var pattern = /o/g; // g modifier stands for global search<br />
var result = “clockwork”.match(pattern); // match is a member function of string object<br />
alert(result.count); // display how many times “o” was found<br />
The actual regular expression pattern is stored between two / symbols. But they are not exactly<br />
the same as double quotes when defining a string. The first / explicitly indicates the start of the<br />
pattern whereas the second / explicitly indicates end. It usually matches end of line character.<br />
112
As you may know an object can contain methods. Remember that everything in JavaScript is<br />
an object. Even a literal string specified with double quotes. In this case, JavaScript has already<br />
provided such a method (called match) to execute a regular expression match:<br />
“clockwork“.match(/o/g) ......... Regex match - returns array: [“o”, “o”].<br />
“clockwork”.toUpperCase()....... Returns “CLOCKWORK“.<br />
“clockwork”.charAt(5) ........... Returns “w” because index counting starts from 0.<br />
“clockwork”.length .............. Returns 9 but this is not an object method,<br />
this is a member variable or object property.<br />
There are a few other methods. In the context of this section we are only interested in the<br />
method called match (also known as object’s member function). The example above shows that<br />
match is not a unique method of the string’s object. And it also shows that it is possible to access<br />
it directly from the string definition.<br />
As you can see we can call all these functions directly after the closing double quote by accessing<br />
the string’s member function with the dot operator. This can be done without having to<br />
store the string within a unique variable first, but by calling it directly on the value itself.<br />
By the way, doing it this way still creates a variable in memory and the value “clockwork” is assigned<br />
to it. It’s just we won’t have a name handle to refer to it once the code is finished executing.<br />
Sometimes this makes the code cleaner and easier to read.<br />
You see, JavaScript already has a number of member functions to help us work with strings.<br />
The function match is not the only one, but that is the one we need in order to execute a regular<br />
expression pattern match.<br />
Remember that this is rather a less common way to execute a command on a string. This is because<br />
we are defining the string “clockwork” on the fly and simultaneously accessing its member<br />
function match. But the exact same thing could be done using the following statements:<br />
var text = “clockwork”;<br />
var result = text.match(/o/g);<br />
The difference is that here we first stored the string “clockwork” in a variable and only then<br />
called the function match. But sometimes it is not necessary to do it this way. The choice belongs<br />
to the programmer and the circumstances in which the code is written.<br />
What else can a regular expression match?<br />
Besides matching the characters from the alphabet we can also match other entities. For example<br />
special characters like #, $, % and others. In addition, regular expressions make it possible<br />
matching character ranges like A-Z or a-z (notice that the letter case matters) and also<br />
113
numeric values such as 0, 1, 2, 3, 5, 6, 7… etc.<br />
Regular expressions let us quickly find a character or a sequence of characters within a string<br />
of text. They make it possible to find patterns searching from the start to the end of the string.<br />
As you may already know a string is just a variable of type string. In other words, it’s text.<br />
Below I am going to demonstrate how regular expressions work with a few brief examples and<br />
visual diagrams. Because our focus is <strong>jQuery</strong> and JavaScript programming, I’ll show you how<br />
Regular Expressions work within this context. But first, let’s see a slightly different, yet identical<br />
(in terms of results) way in which JavaScript allows us to work with regex.<br />
Using the RegExp object<br />
The match method is not the only way to work with regular expressions. In addition to the<br />
match method, JavaScript provides the RegExp object.<br />
Using RegExp, first we will create the object with a regular expression pattern, which is just a<br />
string of text containing the pattern we want to match in another string. Then we will pass the<br />
modifier as a second parameter/argument to specify how we want to search for that pattern.<br />
We can create the RegExp object as shown here:<br />
var regex_obj = new RegExp(pattern, modifiers);<br />
As you may already know, the operator new is used whenever we want to create a new object<br />
of a specific type in JavaScript. In this case we want the RegExp object. Basically it means: create<br />
a new object of type RegExp and allocate enough memory to store all of its methods (internal<br />
funtions/objects) and properties (internal variables/objects).<br />
The pattern parameter is the text we want to match. The modifier parameter is how we want to<br />
match it. For example, modifier can be set to “g” as in following example.<br />
var regex_obj = new RegExp(“lock”, “g”);<br />
The “g” modifier means “global,” and it means that the entire string of text will be searched.<br />
Had the “g” modifier been omitted, the pattern “lock” would only match once, even if there<br />
were more instances of the character combination “lock” in the string we want to test this pattern<br />
on. This just depends on what you want to do.<br />
In addition to the RegExp object method, we can simply define a pattern as follows:<br />
var pattern = /lock/g;<br />
114
Notice that when we do it this way, we no longer use the double quotes to encompass the pattern.<br />
We use the slash /. Also the modifier g is simply added after the second dash. Don’t neglect<br />
the closing semicolon. Even though you can.<br />
By the way, two other modifiers are available which are /i for case-insensitive matching, and /w<br />
for multi-line matching, this is when you have line breaks in the string you are matching the<br />
pattern with. You can use them in combination, for example to match case-insensitive characters<br />
globally, use this pattern:<br />
var pattern = /lock/gi;<br />
Rules of the Pattern Parameter<br />
It’s important to note that I refer to the pattern parameter as a character combination and not<br />
as a string. You see, each character in the pattern is like a command to the regular expression<br />
algorithm. It’s like a language in itself.<br />
In regular expressions, commands are specified using special characters like parenthesis (abc)<br />
or square brackets [cat]. Many other special characters are used to match things in very specific<br />
ways. Herein lies the power of regular expressions.<br />
An example of that would be the use of the square brackets[ and ]. Also known as the bracket<br />
expression. Whenever we place a sequence of characters, such as “abc” within square brackets,<br />
it changes meaning of our search pattern.<br />
The [ and ] brackets will actually not be matched themselves at all, only the characters within<br />
them. The bracket expression is just one part of the regular expression language. When using<br />
them within the pattern parameter, it means the following: match any single character within<br />
the brackets.<br />
So, while the pattern “abc” matches exactly abc in that order, the pattern represented as [abc]<br />
would match either a, b or c. Just one character. Here is an example of how one would instantiate<br />
such a pattern using the RegExp object:<br />
Some other patterns are shown in following examples:<br />
[abc] ............... Find occurrence of any character between the brackets.<br />
[^abc] .............. Find occurrence of any character not between the brackets.<br />
[0-9]................ Find any digit from 0 to 9.<br />
[A-Z] ............... Find any character from uppercase A to uppercase Z.<br />
[a-z]................ Find any character from lowercase a to lowercase z.<br />
[A-z] ............... Find any character from uppercase A to lowercase z.<br />
115
Round parenthesis can be used to search or conditions, with the | symbol:<br />
(clock|work|alex)..... Match either one of the three words.<br />
Note that had the /g modifier been added to the end of this pattern, all separate words or<br />
words containing clock, work and alex character sequences would be matched. But without the<br />
/g modifier, only one word from this series (separated by | character, also known as the logical<br />
“OR” operator) will be matched, whichever one is found first in the target string.<br />
Don’t mix the regular expression’s logical OR operator | with the bitwise OR operator, also |. In<br />
a JavaScript statement the logical OR operator is represented by the double || and the bitwise<br />
OR operator is represented by one |. However, JavaScript regular expressions define the logical<br />
OR operator as just one |. This is simply because the specification for Regular Expression<br />
language also exists in many other languages. And a double || in the context of regular expressions<br />
would look awkward.<br />
As a quick side note, just before we see how strings can actually be matched with this pattern,<br />
consider that the matched results are always returned as an array.<br />
In the case of the latter example (the round parenthesis), with the /g modifier, the resulting<br />
array would return the following: [ “clock”, “work”, “alex” ] if all three words were found in the<br />
target string. Make a mental note, that the “match” function (and it is literally called match(),<br />
as you will see in a moment) belongs to all string objects (that we are about to discuss) returns<br />
an array of matches, even if only one match has been returned, for example: [ “clock” ]. This<br />
value would be stored at index 0 in the match array as in match[0]. If found, the results work<br />
and alex would be stored at match[1] and match[2] indices respectively.<br />
There are many more matching tools at our disposal when using Regular Expressions, including<br />
metacharacters and quantifiers. You can look them up, I just want to keep this tutorial<br />
simple. I’ll probably talk about them as part of my future work.<br />
Matching the Target String<br />
Okay, we now know how to create some of the basic patterns, but how do you actually match<br />
them with real strings? This is shown in the example below.<br />
Remember how we had two different ways of creating a regular expression pattern? One was<br />
using the RegExp object, and the other one writing it into a variable? Here is how you would<br />
execute these patterns:<br />
Using the RegExp object, find the word light in the word enlightenment:<br />
var pattern = new RegExp(“light”);<br />
116
Alternatively, we can create the parameter like this:<br />
var pattern = /light/;<br />
Now that we have the pattern, let’s create the string we want to search and match it with the<br />
value stored in this pattern variable. Notice that I use the member function called match. It<br />
belongs to the string object (the one created as var) I conveniently called :<br />
var string = “enlightenment”;<br />
var matched = string.match(pattern);<br />
Everything in JavaScript is an object.<br />
Objects of type string contain methods that operate on strings. When we define a string with<br />
double quotes an object of type string is created automatically. As we have learned in the beginning<br />
of this chapter, one of the methods that is already integrated into the string object is<br />
called match. This is exactly what we use to match a regular expression pattern with a string.<br />
We can, supposedly also pass a normal non-regex text string to the match function, minus the<br />
special characters like the dot (.) or [ and ] brackets and other special characters:<br />
var result = string1.match(string2); // string2 doesn’t have to be a regex<br />
The argument string2 doesn’t have to be a regular expression. It could be a normal string, defined<br />
using the double quotes. However, a normal string is limited to alpha-numeric characters<br />
only. Regular expressions allow us deeper character search capabilities by providing us with a<br />
number of special characters.<br />
These special characters are like commands that do something very specific. And some of<br />
them can be used to match a previous or next character from current position in the matching<br />
pattern to be determined by the programmer. In other words, they are very versatile text<br />
matching tools that give us control with per-character precision.<br />
Special characters have a unique meaning as part of a regular expression pattern. If your pattern<br />
has the dot (.) character in it, regular expression will not match this as a dot in the target<br />
text string at all. Only a non-regex text string would do that.<br />
But regex sees the dot character as an expression with a special meaning, saying: match any<br />
character whether it’s a number, a letter or any other non-special character. More precisely the<br />
dot means: match most any character with a few very specific exceptions.<br />
117
As part of the regular expression the dot (or the period) character has special meaning. It will<br />
match almost any single character. In order to match the actual period we need to put a backslash<br />
in front of it as in \. or alternatively, place the dot inside square brackets [.]<br />
Putting a backslash in front of a character is referred to as escaping a character. Or in other<br />
words, preventing the special character to fulfil its special function and just match that character<br />
in the provided string instead by treating it like any other matched character.<br />
Escaping a character is a technique that becomes important if we want to match any character<br />
inside a text that would otherwise have a special function in regular expression language.<br />
* * *<br />
Because everything is an object, we can create a string and execute a member function on it<br />
right away. For example, the string “enlightenment” itself is an object and you could immediately<br />
call the member function on it like this:<br />
var pattern = “light”;<br />
var matched = “enlightenment”.match(pattern);<br />
Or you can do it this way:<br />
var matched = “enlightenment”.match(“light”);<br />
Or this way:<br />
var matched = “enlightenment”.match(/light/);<br />
What was matched will be stored in the matched variable. Let’s display it:<br />
alert(matched);<br />
The alert function will display the text string: “light”. You may not find this example very impressive.<br />
We created a string called “light” only to find out that it matched with the word enlightenment<br />
and the result is the same string “light?”<br />
These examples shows only the basic function of how regular expressions work! Had the string<br />
not been matched a value of null would be returned. In other words, using this simple syntax<br />
we can determine whether a pattern exists in a word at all. Consider the code below.<br />
118
if (“light”.match(/darkness/) == null)<br />
{<br />
alert(“No darkness was found in the light.“);<br />
}<br />
This is how we would determine whether there is a match at all.<br />
Moreover, complex regex patterns may not always return the result that matches the requested<br />
pattern (Of course). For example if you tried to match “enlgihtenment” to the pattern [aet] the<br />
returned result would be e. Why’s that? This is because the expression in square brackets only<br />
matches one character out of the entire set. In this case, the string is enlightenment, and the<br />
first letter of this word is e. Because e is one of the letters in the pattern [aet] it will be immediately<br />
matched and returned. The letters a and t are skipped and no longer considered if at least<br />
one of them is matched. However, if /g is added (indicating global search) to the end of the<br />
pattern, both t and e will be matched and the entire set will be returned.<br />
But not only the entire set will be returned with the /g modifier, it will be returned as many<br />
times as each letter is encountered in the word enlightenment. Let’s take a look:<br />
“enlightenment”.match(/[aet]/); ............... Will return array = [“e”]<br />
“enlightenment”.match(/[aet]/g); .............. Will return array = [“e, “t“, “e”, “e”, “t”]<br />
Regular Expression Examples<br />
In order to demonstrate how regular expressions work in a real world scenario, I needed to<br />
find a piece of text that was dense enough with the characters like dots, commas, the end of<br />
line, etc. I thought that a poem or song lyrics fit that criteria. Incidentally, while writing this<br />
chapter I was listening to a song. I decided to use some of the lyrics as the source for the target<br />
string as an example.<br />
Let’s consider the lyrics from Just One Kiss written by The Cure as the source for our string.<br />
You can listen to the song here: http://www.youtube.com/watch?v=7j7IarXmAAo<br />
Here are a few examples of Regular Expression matches. You can print this diagram and keep<br />
it on your desk to help you out with looking things up. Regular expression pattern rules and all<br />
special characters can be a difficult to memorize.<br />
I created this reference to help you visualize the results of each pattern. Please refer to the following<br />
page for the visual examples that dissect some of the most common regular expression<br />
scenarios. Remember that all results are always stored in an array even if only one match was<br />
found.<br />
119
The text string. Pattern Return value (Array)<br />
Remember that time that the trees fell down.<br />
The wood crashing through the wall.<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
/Remember/ [“Remember”]<br />
Remember that time that the trees fell down.<br />
The wood crashing through the wall.<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
/Remember/g [“Remember“, “Remember“]<br />
Remember that time that the trees fell down.<br />
The wood crashing through the wall.<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
/wall/g [“wall“]<br />
Remember that time that the trees fell down. /[wall]/g [“a”, ”a”, “l”, “l”, “w”, “w”, “a”...<br />
The wood crashing through the wall.<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
etc]<br />
Remember that time that the trees fell down. /[.]/g [“.”, “.”, “.”,<br />
The wood crashing through the wall.<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
“.”]<br />
Remember that time that the trees fell down. /A-Z/ Only capital letters. A to Z.<br />
The wood crashing through the wall.<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
[“R”, “T”, “R”, “B”]<br />
Remember that time that the trees fell down. /.*/ Match everything until end<br />
The wood crashing through the wall.<br />
of line. Notice that the match<br />
Remember the sound that could wake the dead.<br />
automatically stops at the end<br />
But nobody woke up at all.<br />
of line, the invisible character.<br />
Remember that time that the trees fell down. /.*/g When g is added, however,<br />
The wood crashing through the wall.<br />
the match does not stop at the<br />
Remember the sound that could wake the dead.<br />
But nobody woke up at all.<br />
end of character mark.<br />
If you understand these commands, you will be able to do some interesting things with strings.<br />
However, these examples are far from definitive. There are thousands of different ways ot select<br />
characters from a string using regular expressions.<br />
If you believe regular expressions can help you with your web project, refer to Jan Goyvaerts<br />
regular expression website at this URL: www.regular-expressions.info This is an excellent free<br />
resource to further explore regular expressions.<br />
120
<strong>jQuery</strong> and Regular Expressions<br />
In previous chapter we discussed Regular Expressions with focus on using the JavaScript<br />
match method. You are probably wondering if there is a way to use a Regular Expressions as<br />
a CSS selector passed to the <strong>jQuery</strong> object. Wouldn’t it be great if we could do something like<br />
the following example?<br />
<strong>jQuery</strong>(“/div class = ‘button’/g“) // match all div elements with class attribute “button”<br />
Unfortunatelly <strong>jQuery</strong> itself does not offer such a solution.<br />
As of the time of this writing the latest version of <strong>jQuery</strong> is 1.7.1, and it does not support Regular<br />
Expression selectors. However, this doesn’t meant that we can’t use Regular Expressions to<br />
sort through HTML elements with <strong>jQuery</strong>. This can still be achieved using the .filter() method<br />
and a little creativity on our part.<br />
Let’s consider these following HTML:<br />
<br />
<br />
<br />
<br />
Let’s say that we want to select only DIV elements that have an id name matching the letter o.<br />
In other words the last two elements. We can write the following code to achieve this selection:<br />
$(“div”).filter(function() { .................. // Filter the matched result set<br />
return $(this).attr(“id”).match(/o/); ..... // Create a Regular Expression rule.<br />
}).text(“matched”); ........................ // Do something with matched elements.<br />
The $(“div”) selector returns a list of all 4 DIV objects obtained from the 4 HTML elements.<br />
Then, using the .filter() method we can further refine this result set by matching it with a regular<br />
expression /o/. In this example we are matching the value of the id attribute with a regular<br />
expression that matches the o character (it will match only the DIV elements with id=”top”<br />
and id=”bottom”.)<br />
Upon execution of this filter, the two bottom DIV elements will contain the text “matched”<br />
which was added using the .text() method at the end of the statement. Of course it would be<br />
possible to run any other <strong>jQuery</strong> methods such as css, animate, etc. on the selected elements.<br />
The advantage of using this strategy is that it requires no external libraries.<br />
121
<strong>jQuery</strong> Callback Functions, the this Property and getElementById<br />
Large parts of this book focus on explainings specific concepts such as CSS selectors, events,<br />
and so forth. But sometimes a number of different concepts must work together in order to<br />
accomplish something very specific. You can simply copy and paste obscure code from online<br />
tutorials. But that doesn’t improve your skills. First understanding and then using these ideas<br />
in combination with one another is what JavaScript development is all about.<br />
Sometimes writing <strong>jQuery</strong> code requires understanding the logic of <strong>jQuery</strong> callback functions.<br />
In particular how the this property is used within the context of callback functions. In fact this<br />
is one of the most frequently used techniques when writing <strong>jQuery</strong> plug-ins or code that simply<br />
stretches beyond the basic understanding of <strong>jQuery</strong> and JavaScript.<br />
In comparison with JavaScript, computer programming languages that are strict, such as C++,<br />
define a very specific set of rules in terms of how they should be used. The limitations of C++<br />
are also part of the brilliance of its design. However, JavaScript is not always easy to understand<br />
because the rules are not strictly defined. You can say that JavaScript is a maleable language<br />
and often, because of its flexibility, it will allow us to invent our own rules.<br />
Even though many modern application are developed using JavaScript, some of the concepts<br />
that you will see for the first time may be hard to understand because of what professional web<br />
developers were able to craft with this language using its flexibility. <strong>jQuery</strong> can be thought of<br />
as such an example.<br />
Some things may not always appear to be clear enough and many people resort to the “copy<br />
and paste” solutions without understanding why the code does what it does. This is especially<br />
true when we start mixing the logical (JavaScript-independent) <strong>jQuery</strong>’s ideas (such as the<br />
syntax of a <strong>jQuery</strong> event function call) with pure JavaScript concepts. Often the mind simply<br />
goes: What is JavaScript? What is <strong>jQuery</strong>? We already know that <strong>jQuery</strong> was written in JavaScript<br />
but where do we draw the line?<br />
The purpose of this section is to explain how callback functions, the this property and the native<br />
document.getElementById function are interrelated and how they work together in helping<br />
us to write effective code.<br />
Let’s consider one of the most common <strong>jQuery</strong> methods called “click” to demonstrate the internal<br />
workings of a generic callback function with a few this-property examples.<br />
$(“div.button”).click(function()<br />
{<br />
var a = $(this); // Here the variable will refer to the selection as a <strong>jQuery</strong> object.<br />
var b = this; // But here the variable will refer to the selection as a DOM object.<br />
});<br />
122
This is probably as simple as it gets. This code attaches a mouse click event to all DIV elements<br />
whose class name is “button” and triggers the code inside the callback for each selected element<br />
when a mouse click is detected.<br />
The <strong>jQuery</strong> object $ is designed in such way that when you pass the native this property it converts<br />
it into a <strong>jQuery</strong> object itself. This means that from now on we can treat the this object as<br />
a <strong>jQuery</strong> object. This is done for at least three reasons:<br />
1. In order to make the code cross-browser compatible,<br />
2. In order to extend the functionality of the native property this, and<br />
3. In order to simplify the syntax of the code.<br />
So, again, by passing the native this object as an argument of the main <strong>jQuery</strong> object ($) we<br />
essentially convert it into a handle to that object which enables us to run <strong>jQuery</strong> methods on it<br />
and benefit from the advantages stated above:<br />
$(“div.button”).click( function() // For each selected element:<br />
{<br />
var a = $(this).attr(“id”); // Get the “id” attribute of whatever was in “this”<br />
var b = $(this).attr(“class”); // Get the “class” attribute of the same element<br />
var c = $(this).attr(“custom”); // Get the value of a custom attribute name<br />
var d = $(this).animate({left: “+=10px”}); // Animate the button by moving it +10px right.<br />
});<br />
Remember that the $(selector) function returns an array of objects to work on. So when we attach<br />
the click method to it using the dot operator we are attaching the anonymous function to<br />
each selected element on that list. All div’s with class = “button” will start receiving this event<br />
from now on.<br />
Notice how the $(this) statement allows us to easily grab the values inside the id and the class<br />
attributes of the selected elements. We have successfully extended functionality of the native<br />
this object. And while the native this property can determine the id value of an element, it<br />
simply does not have the added benefit of <strong>jQuery</strong> methods:<br />
$(“div.button”).click( function() // For each selected element:<br />
{<br />
var a = this.id; // Get the “id” attribute of the native “this.”<br />
var b = this.className; // Get the “class” attribute of the native “this.”<br />
var c = this.getAttribute(“custom”); // Get the value of a custom attribute name.<br />
var d = this.animate({left: “+=10px”}); // Will fail. No such method in native JavaScript.<br />
});<br />
As you can see the native this is not as versatile as when it is used as a <strong>jQuery</strong> object. But both<br />
123
objects refer to exactly the same thing.<br />
Where Does document.getElementById Fit In?<br />
Sometimes dealing with <strong>jQuery</strong> selectors and the this property can be confusing. This is usually<br />
the case due to the illusion created by having to refer to the same objects by different names<br />
and properties.<br />
When we use the $(“div#next”) selector what actually happens is that the native JavaScript<br />
function document.getElementById(“next“) will be eventually called. This process is simply<br />
hidden from us by <strong>jQuery</strong>’s syntax.<br />
But let’s take a closer look at the very first example we used in this section by outputting the<br />
actual values of the native this and <strong>jQuery</strong>’s this object.<br />
$(“div.button”).click(function()<br />
{<br />
var a = $(this); // Here the variable will refer to the selection as a <strong>jQuery</strong> object.<br />
var b = this; // But here the variable will refer to the selection as a DOM object.<br />
alert(a); // Outputs the string “[object Object]”<br />
alert(b); // Outputs the string “[object HTMLDivElement]“<br />
});<br />
Why do the values output a different type of an object? Because they are of a different type of<br />
an object, even though they are referring to the same thing. Remember that the $ function is a<br />
handle to the main <strong>jQuery</strong> object. This <strong>jQuery</strong> library object was created by the developers of<br />
<strong>jQuery</strong> as a custom object. So when we pass the native this, it becomes the <strong>jQuery</strong> this.<br />
However, natively in JavaScript HTML elements actually have unique class names for each element.<br />
For example a DIV element is referred to by the class HTMLDivElement. A <br />
element is referred to by the class HTMLTableElement, and so forth. This is because each<br />
element can do things others cannot. Even though most of them can do the same things, for<br />
example, a DIV and a TABLE can both have a 2px border. But a DIV cannot have table cells<br />
specified using the TR and TD tags.<br />
Notice that the actual object is not a string like “[object HTMLDivElement]”. That’s just the<br />
way the alert function will display a this object when it’s passed to it. The class names of the<br />
DOM objects stored in the DOM tree hierarchy is not used often. However, to shine some<br />
light on the issue, let’s see the rest of DOM element names as natively defined by JavaScript.<br />
124
The following example will demonstrate the common DOM names in reference to various<br />
HTML elements.<br />
<br />
JavaScript DOM Object Class Name Example<br />
<br />
<br />
$(document).ready(function() // Initializate once the entire DOM finished downloading.<br />
{<br />
var List = ““; // Store list of DOM object names<br />
var ElementNames = [“a”, “b”, “c”, “d”, “e”, “f ”, “g”, “h”, “i”]; // Known id names<br />
// Go through each element name and grab the DIV associated with that id<br />
for (var i = 0; i < ElementNames.length; i++)<br />
{<br />
var Name = document.getElementById(ElementNames[i]); // get DOM object<br />
if (i < ElementNames.length - 1)<br />
List += Name + “\r\n“; // Add line breaks to each line except the last<br />
}<br />
alert(List); // Display the list of names for each DOM element<br />
}); // end of $(document).ready<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
Find out what the output of this function is on the following page.<br />
125
The JavaScript example from the previous page will output the following string, revealing the<br />
DOM class names of each individual HTML element:<br />
[object HTMLDivElement] // DIV<br />
http://www.google.com/ // A<br />
[object HTMLParagraphElement] // P<br />
[object HTMLTableElement] // TABLE<br />
[object HTMLSpanElement] // SPAN<br />
[object HTMLElement] // B<br />
[object HTMLElement] // I<br />
[object HTMLFontElement] // FONT<br />
[object HTMLScriptElement] // SCRIPT<br />
Notice that the value of the DOM object referring to the A tag actually returns the value<br />
stored within the HREF attribute instead of something like HTMLHyperlinkElement. Also<br />
notice that the B and I elements share the same class name HTMLElement.<br />
Keep in mind that $(this), the native this and getElementById, in the end all refer to one and<br />
the same object. In JavaScript the only real object associated with an arbitrary DIV element is<br />
of type HTMLDivElement. That’s all that there is. All variables, $(this) and this references are<br />
merely handles to that object.<br />
Finally, it should be noted that variables, such as var c above are not object themselves. They<br />
are simply handles to an actual object stored in computer memory.<br />
Use variables and references to objects as tweezers. Pick the objects you need to work on and<br />
apply <strong>jQuery</strong> methods to them. Keep working on your program and try to find ideal ways to<br />
create logical constructs that control the flow of your computer program.<br />
126
Making Good CSS Buttons<br />
This tutorial is a preview of the content from my tutorial e-book. This is from Revision 3 that I<br />
am currently working on right now. The book contains the expanded version of this tutorial.<br />
A website that has an original look stands out from the rest. CSS buttons therefore are important.<br />
Perhaps they are even trivial to implement using basic CSS and <strong>jQuery</strong> events. However,<br />
creating any high-quality work requires a thorough examination of the ingredients.<br />
In this tutorial we will create custom CSS buttons that may look like this:<br />
Or how about navigation bar buttons like these?<br />
The buttons shown here are 3 times the original size. These sets can be accomplished using<br />
simple CSS styles. But the most important ingredient of a good looking button is attention to<br />
detail. We can’t carelessly slap gradients and colors onto a button. There is something subtle<br />
about how the human eye picks up on the smallest details.<br />
But first, a little history.<br />
In the past, when it came to creating buttons our choices were limited to HTML’s and<br />
tags. Their extent ranged from using the default button rendered by the browser itself<br />
to using custom images as the background of the button element. In addition the programmer<br />
could simply wrap an tag with an tag and remove the border of the image by setting<br />
it’s border attribute to zero as in border = 0.<br />
These techniques still work. But they have many flaws. For example on older Windows (that<br />
may still be in use today,) the default button would appear as a plain button in gray color. On<br />
the newer Windows operating systems the native button looks better, but it may not always fit<br />
the theme of the custom website or UI you are developing.<br />
With text using basics font like Arial or Verdana which is almost the only thing you can<br />
change about the default HTML buttons, we are stuck with the limitations of the native button<br />
design.<br />
127
But we are not in the 1990’s anymore. These shortcomings have since evolved. Modern buttons<br />
are created using CSS styles, <strong>jQuery</strong> and Ajax. The HTML and CSS elements of a button<br />
represent its visual style, of course. <strong>jQuery</strong> is used to dynamically change the appearance of the<br />
button depending on whether the mouse cursor is over or out of the button’s HTML element.<br />
And finally Ajax is used to execute some function on the server once the button is clicked (like<br />
a PHP file that returns a value). Of course, the action that occurs when the button is clicked on<br />
could have been just a client-side JavaScript function. In fact, that is probably what most buttons<br />
are used for. However, linking button actions to Ajax events that run some type of a script<br />
is not uncommon. Buttons come in different types and flavors. What should happen when a<br />
button is clicked is usually determined within a function known as a callback function.<br />
$(“div#my_button”).click( function() { /* Do something */ } );<br />
Here the callback function is highlighted in yellow. As you can see, it is passed to <strong>jQuery</strong>’s click<br />
method as the only argument.<br />
Choosing the Base Element: DIV or A<br />
Let’s create a rule. All elements that are buttons will inherit the CSS class “button.” In other<br />
words, in order for the web page to consider an HTML element a button we will apply the class<br />
named “button” to that element using the class attribute as in:<br />
or <br />
Does it have to be this way? Of course not. But you are the developer, you create these rules.<br />
For the purpose of this tutorial I chose to do it this way, but it’s certainly not a universal rule<br />
cast out of iron or stone for creating CSS buttons.<br />
The button we are about to create is going to have a base element. We can use any blocking<br />
(commonly for buttons positioned with position: absolute) or inline elements (for buttons<br />
positioned with position: relative) such as or to represent our button.<br />
128
Sometimes it makes sense to make the button out of the tag (which creates a hyperlink)<br />
and simply re-style it into a button and mute HREF functionality. You may think that is<br />
a convenient choice because by default the tag is already clickable. However, this is not a<br />
good reason for choosing the tag to create buttons at all. In fact the default clickability of<br />
the tag should be muted entirely if we want it to serve as a CSS button.<br />
Later on you will see that we will override all button events using <strong>jQuery</strong>’s .bind() method<br />
instead of using the href or onclick attributes. Doing it this way makes it easy to switch to DIV<br />
later on if in fact you do run into some type of a CSS style conflict that has to do with element<br />
tag name collisions.<br />
Let’s compare the two HTML tags that can be used to spur the roots of HTML button creation:<br />
Okay<br />
Okay<br />
Normally, we should reserve the tag specifically for hyperlinks to avoid clashing CSS<br />
styles between hyperlinks and buttons that may be added later on in our project.<br />
We can, however create a special button and refer to it by its class name. Such a button can be<br />
created using the A.button {...} style as in Okay) as long<br />
as we promise ourselves that all buttons will be created this way (to keep our CSS files organized<br />
and easier to work with).<br />
Working on a serious web project your responsibility is to do everything in your power to<br />
ensure that the buttons created using the tag will work the same and look the same in all<br />
browsers. While I try to maintain at least some cross-browser compatibility in my tutorials you<br />
can say that this tutorial is mainly limited to the Chrome, Firefox, Safari and the latest version<br />
of Internet Explorer browser.<br />
Writing a different tutorial for each browser could interfere with the fundamental concepts<br />
presented here and I think one could write an entire book talking about the differences between<br />
browsers alone.<br />
Keep Things Simple At The Root<br />
Choose one tag. But don’t choose both (A and DIV) to represent different buttons. Sticking to<br />
one tag may prevent future confusion. Within the context of this tutorial I am going to explain<br />
the details of using both: the tag and the tag to create buttons which are pretty<br />
much the same minus some trivial differences.<br />
129
The DIV tags don’t have to deal with the HREF attribute. Aside from that the two tags will<br />
produce identical results. However, for this to be true within our script there are a few things<br />
you should know about the tag.<br />
Dealing with A and HREF<br />
The tag has the infamous HREF attribute which is used to specify the destination of the<br />
hyperlink. But we don’t want a button created using the tag to go to a web page. In other<br />
words, we want our universal button to be able to respond to a click event. But we don’t want<br />
to do that using the onclick attribute either. After all, this is a <strong>jQuery</strong> tutorial and <strong>jQuery</strong> offers<br />
the convenience of using events which are accessible within a single point in our JavaScript<br />
code. Being able to access important code from a single point in our script will save time<br />
working on our application in the long term.<br />
<strong>jQuery</strong> allows us to bind events to our buttons and this code will always be stored in the same<br />
place during initialization of our web page (let’s say within the $(document).ready event.) This<br />
will prevent us from having to jump from one onclick element to another throughout the entire<br />
HTML part of our web application. And when the time comes to deal with modifying button<br />
functionality in the future we can always refer to that single place in our code to modify<br />
button functionality. And save ourselves a headache.<br />
Let’s now talk more about the HREF attribute. As we just discussed we will be using <strong>jQuery</strong><br />
events instead of onclick and HREF attributes. This means that we need to figure out a way to<br />
completely disable HREF.<br />
You probably already know that when instead of providing a URL we can use the number<br />
symbol # followed by a custom anchor name (like #Paris) as HREF value. This will make the<br />
vertical scrollbar “jump” to the anchor location named “Paris” on your website. In other words<br />
Clicking on this link: Go to paris the page will jump to a location<br />
marked by this code:<br />
Travel to Paris<br />
We can simply use just the # symbol as in Return to top of the page and this<br />
way, seeing how the anchor name is not provided at all, the web page will jump back to the<br />
very beginning.<br />
This is the default hyperlink functionality. But we want this to be completely disabled for our<br />
button. We don’t want the button to go to any URLs or anchors. And we definitely don’t want<br />
our button to jump back to the very top of the page when it’s clicked. But we do want something<br />
to happen when a button is clicked using a <strong>jQuery</strong> event. We’ll discuss that momentarily.<br />
For now let’s disable the HREF functionality completely by doing one of the following:<br />
130
1. Specify javascript: return false; as the HREF value, as in href = “javascript: return false;“<br />
2. Specify return: false as the value of the onclick attribute, as in onclick = “return false;“<br />
3. Remove HREF attribute from the tag. Example Okay<br />
All 3 techniques will disable the default HREF function of the A tag.<br />
You may have not expected technique 3 to work. But in my tests, it worked without a problem<br />
in Chrome, Firefox and Internet Explorer. In other words, by not specifying the HREF attribute<br />
at all we are telling HTML that this is just an anchor, not a hyperlink.<br />
The behavior of the A tag depends on the presence of the HREF attribute within the tag. With<br />
it, it behaves like a hyperlink. Without it, it behaves like an anchor. Essentially by skipping<br />
HREF we are turning the anchor into a button, not the hyperlink.<br />
The cursor pointer icon is also dependent on the existence of HREF attribute within a tag.<br />
When you hover over the HREF-less tag with your mouse it will no longer turn into a proper<br />
pointer cursor. It will turn into a text-selection cursor. But that’s not a problem. We can re-add<br />
the correct mouse pointer cursor back again by forcing the CSS style on our buttons as in:<br />
A.button { cursor: pointer; } /* Getting the mouse pointer back into a HREF-less A */<br />
That works. But wait. Let’s take care of one more thing. The tag used for buttons might<br />
still be rendered as a hyperlink. This means it will display an underline text decoration under<br />
the button’s name which is the text printed inside the button. This of course wouldn’t happen<br />
with a DIV. But in order to prevent that from happening in an A tag, let’s also remove the text<br />
decorations by enforcing the following CSS style on all buttons whose class is “button”:<br />
A.button { text-decoration: none; }<br />
Once we handle the HREF tag by applying the aforementioned CSS styles to our A-tag based<br />
buttons we are pretty much left with the equivalent of a DIV tag. At this point this stripped<br />
down A tag will behave in the same way as a DIV-based button would.<br />
From this moment on, given that we understand the changes we just made to the A tag, we can<br />
continue the discussion of creating custom buttons in such way that would apply to both the A<br />
and the DIV tags equally in the same exact way.<br />
Choosing the DIV tag as the base element for our buttons saves us from having to deal with<br />
“preparing” the A tag for turning it into a button. Which tag you will use in your web application<br />
for creating CSS buttons is up to you. Just make sure that you stick to one tag to avoid<br />
complications later on.<br />
131
Whichever tag you will use to create your buttons, one thing is clear. We will simply use the<br />
<strong>jQuery</strong>’s .click(...) method or “bind” the click action using the .bind(...) method to the anonymous<br />
callback function that will execute the code when the button is clicked.<br />
I think we are equipped withe enough knowledge to start experimenting with the code.<br />
Let’s walk through the process step by step and create a few buttons. First, we need to determine<br />
the HTML and CSS. We already discussed that the button will be defined using either<br />
the A or DIV elements. Either way, notice the class=”button” is present.<br />
Okay<br />
Cancel<br />
Delete<br />
Alternatively, you can use the DIV tag. Notice the abscence of onclick attribute in either case.<br />
Okay<br />
Cancel<br />
Delete<br />
Button CSS Styles<br />
Now let’s write the CSS. To add interactivity to our button we want to have at least 3 different<br />
CSS styles for mouseover, mouseout and mousedown events.<br />
Default Style<br />
First we will need to determine the main CSS style which will describe the color, border style<br />
and the gradient of the button. This is the default style that will be applied to all buttons:<br />
The button displayed here is several times larger for clarity.<br />
132
Our goal is to match the button with the theme of the rest of the website. That’s entirely up to<br />
you and your sense of design. Let’s take a look at how border-radius can change the appearance<br />
or “feel” of the entire button.<br />
Aside from the three examples above using border-radius that is far greater than half of the<br />
button’s height will result in an angle that makes a perfect circle, making both sides of the button<br />
perfectly round. That’s why in the Default Style we started with I set border-radius to the<br />
value of 32px. Half of our button’s height is far less than that because it’s just an A element. But<br />
if we provide a value that is larger than half of the height of the HTML element the roundness<br />
of the button will reach its maximum and stop there, looking like half of a perfect circle.<br />
Button style is a personal choice. You can change the border-radius value to anything you<br />
want. Simply experiment with different values until you achieve something that looks good.<br />
On Hover<br />
When we hover the mouse pointer over the button, we want the button to change its appearance.<br />
One of the best ways to achieve this subtle effect is by slightly changing the color of the<br />
border, the font color and adding an outset shadow using the box-shadow property:<br />
The .buttonOn class does not need to define all of the values of the Default Class because it<br />
will simply inherit all of them from A.button. What we need to do is to overwrite some of the<br />
values. I indicated new box-shadow property and the overwritten properties in red color.<br />
133
The new color #bbbbbb is probably not very far from #cccccc of the original button. But you<br />
have to believe me that these subtle adjustments make the experience of using the button feel<br />
much more elegant.<br />
The idea is to apply subtle changes. It is therefore a good habit to avoid changing style properties<br />
from one extreme to another just because we have hovered the mouse cursor over the button.<br />
The same goes for the font color. We apply a subtle, almost invisible change on hover.<br />
Pressed Down<br />
And finally we need a third style that is applied to a button when the mouse button is pressed<br />
down. I have experimented with an inverse gradient. However, the button in this state looked<br />
much more elegant if I simply made the background a solid gray color.<br />
After conducting a few CSS experiments I have determined that the optimal styles for all three<br />
states should look close to something compared to what you are seeing below. So far we have<br />
arrived at these three styles:<br />
Of course, we don’t have to stop here. You can continue applying further changes to match the<br />
buttons with the theme of your website. But this is a very good base to start with.<br />
134
So far, we have briefly discussed the CSS code for creating three different button states. I even<br />
mentioned the linear-gradient property in the very first example. But even though the CSS<br />
property linear-gradient is a WC3 standard, it will not work in Chrome.<br />
I wanted to find a way to easily create gradients without having to define solutions that worked<br />
in all browsers by hand. Moreover, I needed a solution that would produce the same results in<br />
all browsers. After a quick Google search, I found what I was looking for.<br />
The CSS code gradient for the background of the buttons was created using this extremely<br />
powerful online CSS gradient tool. It makes sure the gradient looks the same in all browsers.<br />
In addition, you can simply copy and paste the generated code into your CSS file.<br />
Instead of cluttering the page with the source code listing for the entire CSS, let me give you a<br />
link to the actual button.css file which describes the styles we have discussed in this section.<br />
Download buttons.css<br />
http://www.learnjquery.org/book/sourcecode/buttons.css<br />
Now that we have A.button, .Hover and .Pressed defined we can use <strong>jQuery</strong> to program the<br />
logic of our buttons. We have discussed <strong>jQuery</strong> events earlier in the book. But in addition to<br />
events we will use <strong>jQuery</strong>’s methods .addClass and .removeClass to dynamically add and remove<br />
the CSS classes we have just created when a mouse event (such as mouseover) occurs.<br />
Attaching Mouse Events to the Buttons<br />
Let’s take a look at a very simple <strong>jQuery</strong> event system that will switch the CSS classes of our<br />
buttons depending on whether the mouse is in over, out, pressed, and released state.<br />
$(document).ready( function() {<br />
// What should happen to all .button elements when the mouse is over the element?<br />
$(“.button“).mouseover( function() {<br />
// Add .Hover<br />
$(this).addClass(“Hover”);<br />
});<br />
// What should happen to all .button elements when the mouse is outside of the element?<br />
$(“.button”).mouseout( function() {<br />
// Remove .Hover and also remove .Pressed if it was present from a previous action.<br />
$(this).removeClass(“Hover”).removeClass(“Pressed”);<br />
}<br />
135
What should happen to all .button elements when the mouse button is pressed down?<br />
$(“.button”).mousedown( function() {<br />
// Add class .Pressed<br />
$(this).addClass(“Pressed”);<br />
}<br />
// And finally, what happens when the mouse is released?<br />
$(“.button”).mouseup(function()<br />
{<br />
// Remove class .Pressed<br />
$(this).removeClass(“Pressed”);<br />
});<br />
}); // End of $(document).ready<br />
We just linked the mouseover, mouseout, mousedown and mouseup events with the previously<br />
created CSS button styles and took care of all special cases. For example, notice that the<br />
mouseout event also removes class .Pressed from the button. This is necessary because when<br />
the mouse cursor leaves the button element from a pressed state it is important to return the<br />
button to its default style again. If we didn’t do that, the button would continue to look like it is<br />
still pressed even though the mouse curors is no longer on it.<br />
Running this code inside $(document).ready(...) is important because we only need to attach<br />
these events once. We use .addClass and .removeClass accordingly inside of each callback.<br />
From this moment on, you can physically change the CSS style of each button and the functionality<br />
will remain the same. If you need the buttons to look different than the ones in this<br />
example you should easily be able to modify them without losing the event functionality.<br />
136
Note from the Author<br />
Looks like you’ve come to the end of the book.<br />
On July 12 2012 the book has grown by about 30 pages and finished being distributed for free<br />
to everyone who has purchased the original copy in April. This does not mean that the book<br />
can be distributed for free to anyone. Only that you have to purchase it once to receive all future<br />
updates for free. You have purchased a single license to use this book.<br />
As of July 12, 2012<br />
Most important corrections have been applied, and a great amount of new content has been<br />
added. However there are still syntax errors and things I’d like to fix. Perhaps even add a few<br />
more chapters. I wouldn’t feel completely satisfied until Revision Three which is what I will be<br />
working on in the coming months. For now, I ask you to remain patient and continue following<br />
my free <strong>jQuery</strong> newsletter if you are a current subscribers.<br />
My plan is to continue applying new edits and adding new content to this book throughout<br />
the remainder of the year 2012 and shape it into something more definitive, something that<br />
has raw information and solid educational material readers can learn from. Those who have<br />
already purchased their copy don’t need to buy the book again just because new content was<br />
added. They will receive new updates by e-mail. There is nothing else you need to do.<br />
* * *<br />
When I had the idea to write a book, I wanted to create a volume of interesting and useful insights.<br />
We already have plenty books that simply go through one feature after another offering<br />
examples of code and listing functions. My goal was to create a fluid experience, cover many<br />
different subjects and relate them to one another.<br />
In addition to this book you can subscribe to my free <strong>jQuery</strong> e-mail newsletter. The link is<br />
available from the book’s homepage: www.learnjquery.org<br />
I hope that you have enjoyed this book.<br />
If you have any questions regarding the code examples please feel free to write me an email:<br />
greg.sidelnikov@gmail.com<br />
Book Website Twitter Facebook Google+<br />
Thank you for reading.<br />
137