Friday, April 20, 2012

When is a Phone Not a Phone?



On January 9, 2007, Steve Jobs addressed a group of adoring Mac heads at the annual MacWorld conference. He talked about how Nokia had pioneered the mobile phone industry and created some of the best mobile phones in the market. He talked about how Blackberry had changed the world by creating devices that excelled at getting e-mails anywhere in the world securely and quickly, allowing you to respond to them instantly. He talked about how desktop computers were fantastic for browsing the Web, but no one had quite captured that desktop browsing experience in a handheld. Steve then showed the world the first iPhone—the world's first phone, e-mail, and mobile Internet device. The moment I saw it, I knew I had to have one.
I am, and have been an unabashed Apple fan. Both my parents were teachers and were able to check out Apple computers from the school library during the summer. This meant that I spent almost every summer of grade school in front of a monitor with the Apple logo on it. The iPhone was the culmination of all of those summers' enthusiasm times one thousand.
I went to the Tampa Apple Store after work on the day of the launch and I was the first one on my block to have a new iPhone. The data speed was excruciatingly slow and the phone dropped calls more than a freshman football player drops passes, but the device revolutionized what we thought a handheld could be. And with each release, the iPhone continued to get better. As it had done three decades earlier with the personal computer industry and two decades earlier with the GUI, Apple had ignited innovation in the handheld space that the world would never be the same.
Some five years later, it's impossible to imagine a Friday night without texting your friends and getting information on which restaurant in the area serves the best Persian Kebob, and then sharing the location with them all, so they meet you there without a single phone call exchanged between you. We live in a handheld world and many a pundit has stated, "If you don't have a mobile strategy, you don't have a strategy".
So, what is your mobile strategy? Whether you sell cupcakes on Main Street to 12-years-old girls, or servers to wall street traders, Drupal gives you a framework to create a first-class mobile website.
Drupal is an open source piece of software installed on servers that allows you to manage content for a website through a web-based interface. You can pair your content with one or more themes, which will wrap the content in the HTML design of your choice.
There are tons of better CMSs out there, both paid and open source. What makes Drupal what it is today are two basic things—one is the hundreds of thousands of developers contributing modules to the Drupal framework. Second is Drupal's approach. Drupal approaches web development as a series of Lego™ blocks, each one building on the other until the entity becomes greater than the sum of the parts. This book will attempt to demystify the process.
So what is it that you hope to accomplish with your mobile site? The chances are that it's one of the following three general goals:
 
?? Broadcast message: Includes either news or information. Allows you to share information about your business or non-profit with current or future customers.
?? Interaction: Allows your customers to find you, contact you, or in other ways, interact with you.
?? Location portal: For example, find the best Kebob in Arlington, Virginia.

 
What you hope to accomplish will give you a better idea of who your audience is and what type of hardware they might have.

"Dumb" phones
In the beginning mobile telephones were large bricks that needed constant charging and had a very limited range. By the year 2000, Nokia and Motorola had most of the US Phone market selling what we now call "dumb" phones. Dumb phones were dubbed, thus, as a reaction to newer "smart" phones. They usually have a single color screen and a 12- key standard phone keypad with a power on and off button and maybe one or two other function keys. You can accomplish text input with a combination of presses on the keypad.
The phone's secondary features such as storing phone numbers and texting are usually accomplished through a series of menus. The browsers on these phones use a protocol called Wireless Application Protocol (WAP). WAP was evolved by necessity on these "dumb" phones in the early 2000s. WAP breaks up the content into a series of menus and text cards, and you can use the menus to navigate through the text cards to achieve something approaching a wireless Internet experience. Unless you know for sure that your audience is using WAP-only phones, you can probably choose to disregard it and author your site in HTML only. This book will only touch briefly on the WAP protocol and will turn most of its attention to full HTML sites, as the vast majority of mobile web traffic in the US and Europe are smartphones using WebKit-based full-HTML browsers.




However, there are some places where "dumb" phones in the US excel and are readily accepted. These include the following:

·        Government jobs that require that your cell phone does not have a camera
·        Many Health and Human Services buildings that deal with minors and much of the court system has security in place that doesn't allow cameras in the building
If you have a cell phone with a camera, it's confiscated by the security guards and given back to you when you exit. After having my cell phone confiscated at the door on a trip to traffic court recently, I noticed many of the lawyers in the building were carrying phones that look like they were from another era. As long as security measures such as these are in effect, there will always be a market for the circa 2001-era "dumb" phone with a T9 keyboard and a WAP web browser.
 
"Smart-er" phones
So between the "dumb" phone and today's high-end smart phones are what the industry calls "Smart-er" phones. They usually have color screens and a keyboard that enables faster SMS communication, but don't have the processing power or storage capability of a fully-fledged smart phone. Recently, cheap Android-based smart phones have supplanted these phones, but there are still a few of them in the market. They mostly use the WAP protocol that the dumb phones use, but with a few exceptions.
So, as with dumb phones, unless you know for sure that your audience is using these devices, you can eschew WAP and turn your attention toward building sites with standard HTML.


Smart phones
About a year after the iPhone was released, word leaked out onto some blogger sites that Google was creating an open source operating system for phones. Based on Linux, the new OS would be made available free of charge to handset manufacturers and would also offer some of the advanced functions available to iPhone owners. Google would also allow developers to submit their applications to a common market where users of the OS could purchase and download these. The industry was instantly a buzz. Android adoption started out slow, but as the OS improved, more and more manufacturers started releasing phones with their tweaked version of the Android OS. The touch screens and features on a par with the iPhone at a fraction of the cost and on the carrier of their choice drove Android to success and made millions for Google in search revenue. More than that, it gave the iPhone some competition - and competition almost always drives innovation.


Android's greatest strength was also its greatest weakness. Anyone could alter the OS and put it on their handset, which means that programmers had to contend with changes in the configuration from a multitude of hardware sources. When writing custom applications for the handheld, testing, and vetting each of the hardware configurations was, and continues to be, a nightmare for Android developers. And the submission process for applications to the Android App Store was not nearly as streamlined as for Apple's App Store. But creating a truly cross-hardware version of your application needn't be a lesson in patience.
 
Tablets
Just as earth-shattering as the iPhone announcement was Apple's release of the iPad. Tablet computing has been around for a number of years, but with a stripped down version of Windows as its OS. Many users rejected tablets as they considered them reductive - "less" of a computer than their desktop - and they never really caught on.
The iPad was all about more. It was like an iPhone, but more than that. Like a laptop, but without a clumsy fold-out keyboard and the battery lasts for 10 hours.
Since then a myriad of Android tablet-style devices have been released with a varying amount of sales success, but as of the date of this book's printing, the iPad remains king of the tablet world and will for a number of years in the future. There's some marketing research to suggest consumers are buying tablets in situations where they normally would have bought a laptop for $500, and with the emergence of cloud computing, it makes sense to forgo a bulky laptop in favor of a lightweight tablet.
Now, I have replaced my laptop with a 3G iPad that is always connected wherever I go. It's possible for me to travel for days without touching my laptop and do almost everything I could do with it, including administering servers, writing code, and authoring this book.
The emergence of the tablet is one of those decade-definer events along with the social networking, the Internet, and the personal computer before it, that would change the landscape of computing in ways that no one could predict.

WebKit
Although the Android platform and iPhone differ greatly, there's one very important similarity - their web browser. Both OSs have their web browsers based on the open source WebKit project.
In 2001, Apple needed a small, lightweight web browser for it's new Mac OS X operating system. They chose a little-known open source project called KHTML for its clean code, support of web standards, and minuscule (for a web browser) codebase. KHTML was basically a set of libraries you could use to render HTML documents in Windows. From the KHTML project, Apple spun off the WebKit and created their Safari web browser, and a few years later, Google created their Chrome browser from the same set of libraries. Because of its modern compact rendering engine, Safari was able to leapfrog Firefox and Internet Explorer in its support for emerging standards. It became the logical choice for both Apple and Google's handheld operating systems. When Blackberry updated its operating system to enable touch screens, they also chose the WebKit rendering engine, so when you're developing for mobile browsers, with a few exceptions, you're basically developing for WebKit, which makes life significantly easier than developing sites for the desktop. WebKit boasts some of the best rendering of CSS and HTML and some of the fastest JavaScript of any web browser.
 
Mobile size me!
But more often than not, you purchased this book because you have a particular website in mind that you need to "make mobile". I encourage you to rethink parts of your website that no longer make sense in light of a mobile paradigm. Things such as hover-based navigation, photo galleries of large-sized images, music, flash, or high-speed repeating animation on the home page will frustrate your mobile users for reasons we will make clear. So to "mobile-ize" your website, you may need to do more than just come up with some slick tricks and mobile-friendly CSS to make the mobile experience of your site first-rate.
Throughout this book, we will be working through an example website. Chapter 2, Setting up a Local Development Environment, will get the example set up, but if you have an existing site, feel free to set up a development environment of your own and add mobile additions to your existing site. The book is set up to work through the example adding features one-by-one, but the chapters will be generally self-contained and you can take them a la carte.
All-in-all, there are about 6500 different web-capable mobile devices. We will attempt to create a site that is viewable on the vast majority of those devices.
But all of this begs the question that is discussed in the section that follows.

What is mobile?
Is mobile just a piece of hardware? We've talked about hardware, some of the software, iOS versus Android, and WebKit versus WAP browsers. But what exactly is "mobile"?
Mobile is a context—the context of the user rather than the context of the computer. With most computing, the assumption is made that it will be done on a desktop or laptop and there will be a storage device, a display device, and multiple user inputs such as keyboards, mice, and trackpads.
Mobile relinquishes those assumptions and assumes only the user. Nothing about the device and screen may be assumed, because we could be talking about a mobile phone with a four-line screen and WAP browser. Nothing about the keyboard can be assumed because very few mobile phones have physical keyboards these days.
A "mobile" website must be adaptive and able to be displayed wherever and whenever the user needs or wants to and cannot make any hardware or software assumptions.
And that is why, in my opinion, it should be a different website from your standard desktop version.
The theme-ability of the content and agile nature of the CMS make Drupal a perfect tool to solve some of these design challenges, as you will soon see.
 
The "One Design" myth
So there's a theory of design. It states that we should design the website so that all the pieces work together in both a desktop context and in a mobile context. Use smaller design pieces that are adaptable to small screens and use CSS that will optimize the display for whatever the user chooses to view the website on. This is sort of a "one ring to rule them all" mentality.
I would disagree with this strategy. Not only is this an incredibly difficult task for a designer, but I think this approach overlooks a basic constraint. The ways in which we consume information on a desktop machine and that on a handheld device are completely different.
I believe the act of reading itself is completely different for all. More than that, I find the websites on which I'm most compelled to view content have two versions (a desktop version and a mobile version).
Feel free to disagree with me, but this is primarily the approach we will be taking in this book. And with Drupal as the CMS, you will see this approach becomes easy with the addition of contributed modules that separate content and allow different themes and JavaScript for different domain names.
For every rule there is an exception and there is, indeed, a place where the two-pronged site approach breaks down. Designing a website for tablets requires aspects of mobile design, a clear attention to touch events, and a design that's not quite tailored to the desktop and yet not quite a mobile phone.
We will discuss the ways Drupal can power your tablet strategy and try to cover the gap between the smaller mobile site and the full-version desktop site.
 
Mobile simulators
Before we set up a development environment, we need to set up a simulation of our mobile devices. We do that with either of the two packages—the Android development package or the XCode/iOS development package. XCode is available for Mac OS X only, but the Android development environment is Java-based and will work with any modern OS that has a Java Development Kit installed.

Time for action – installing an Android development package
 
1.      To download and install the Android development package, go to java.com and download the Java Development Kit (JDK). Just having a regular Java package installed is not enough. You need to install the developer tools, too. Go to http://developer.java.com and search for the JDK developer download.
It will be a .exe file. Run the installer:



2.   Once JDK developer is installed, the next step is to get the Android development tools. These are available at http://developer.android.com. Download the exe version of the Windows installer.
3.   After the first Android installer runs, it will launch the Android Software Development Kit (SDK) and Android Virtual Device (AVD) manager. Yes, I know these are a lot of acronyms. Java developers love their three-letter acronyms. The SDK and AVD manager will ask to download the various android platform-specific APIs. Go ahead and choose the default options. Android will go through a series of downloads and install them after they are downloaded:


4. We then need to create an Android Virtual Device. Click on the Virtual devices tab and then click on the New button. Let's create one for Phone emulation and one for tablet.
5. Name the first one phone and select Android 2.3.3-API Level 10 (which is the latest, at present).
6. Choose a screen size. The QVGA skin should work for most phones. Then click on the Create AVD button to launch the Virtual Device:


What just happened?
One of the current problems with the Android platform is called fragmentation. This means that there are a lot of devices that have been sold with various versions of the software on them. As Google produces new distributions of Android, some devices get the updated versions and some do not. Depending on how much the device manufacturer and carrier have customized the Android software, they may make the decision that it's in their best interest to force the user to upgrade to a different device rather than to distribute the updated software to existing devices.
As a developer, if you create an Android application, you have a situation where there are hundreds (maybe thousands) of different combinations of hardware and software to test with your application. In addition, because of the open source nature of the Android OS, each manufacturer of hardware has the ability to alter the Android experience. This includes adding applications that showcase their hardware's features and adding APIs that allow their phones to connect to special networks or services that only they offer. As if that wasn't enough, phone hardware manufacturers often alter the hardware or software of a phone in response to a request from the phone carrier. Verizon is known for not allowing certain phone features to be used without their permission or to be used in a way that allows Verizon to charge for the service.
The myriad of combinations of hardware, hardware manufacturer additions, Android-based OS versions, and carrier additions has the ability to make potential Android developers homicidal. Google is taking steps to minimize fragmentation, but at present, we have a hodge-podge of customer conditions that can only be described as "less than optimal". This makes mobile web development that much more compelling because the version of WebKit that ships with them has very little differences between the various software updates.
 
iOS
As a platform, iOS has the same problem with fragmentation that Android does. Their application development has a tendency to be a bit tyrannical. No software can be installed on an Apple device without first being submitted to the Apple's application review process.
Legend has it that Steve Jobs' insistence on Apple's control over the user experience was a big stumbling block for Verizon and Sprint in the early days of developing the first iPhone and it led to them pairing with AT&T in the US for its initial release. Once the iPhone released and was being sold very well, AT&T asked Apple to limit the amount of YouTube videos or the quality that could be played on an iPhone. Apple's response was something to the effect of "No, we're not dumbing down our user experience for you." Apple's laser beam focus on the user and user experience is simultaneously iOS's biggest draw and its greatest developer gripe.
There's an active community who regularly jailbreaks iOS devices, or rather enables applications from other sources to be installed. In terms of numbers, it represents a ver  small proportion of total iOS device users and there's always the possibility that jailbreaking your iOS device could lead to "bricking" (Apple rendering the device useless or "like a brick").
And bricking your iPhone is, most assuredly, not covered under the warranty.
All software on an Apple device is written in Objective C. This is a dialect of the very popular and proven C programming language that's pretty much only used by Apple. When faced with learning a completely new programming language and Apple's API additions to the language, combined with Apple's App Store policy and the fact that any application you develop has no guarantee that it will be accepted and appear in Apple's
App Store, many developers, again, turn to the mobile web.
Mobile websites need only a URL to be visible from any iOS device. But the quirks of the iOS web browser—Mobile Safari—make for a lot of trial and error JavaScript and CSS.
Fortunately, Apple has mobile web simulation software available with its iOS developer toolkit that will allow us to preview our site before uploading our changes to the live version.

Time for action – installing the Mac OS developer's package
1. In order to download and install the Mac OS developer's package, you first need to register with Apple as a developer. Go to http://developer.apple.com/programs/register/
2. If you have an iTunes username and password, you're welcome to use it or create a new one specifically for your development work. There are two options. You can register as an iOS developer, which costs $99 for a year and allows you to submit iOS applications to the iOS App Store. If you're not planning on doing any iOS development, you can simply download XCode 4 from the Mac App Store.
3. Once you've gone through the free registration at Apple's site, launch the Mac App Store and search for xcode.


4. Once XCode is installed, you can use the Mac's computer-wide search to find the iOS Simulator, as shown in the following screenshot:


5. Launch it and click on the Mobile Safari icon in the bottom tray. Go to http://dpk.local . It should appear in your desktop browser, as shown in the following screenshot:


What just happened?
Debugging CSS and JavaScript for web pages is never easy. It's made even more difficult with the proliferation of desktop operating systems and, now, handheld and mobile operating systems. No matter which browser claims to have "emulation" or modes that simulate this other browser or that, it's not a substitute for looking at the web page in the actual browsers. Debugging pages in Internet Explorer, requires an install of Windows XP and the browser itself. Don't settle for anything less. With handheld devices, you really need a virtual environment where the handheld OS is running a real version of the browser.
In this exercise, we created such a virtual environment. The XCode package creates the environment for the iPhone and iPad, and the Android development environment creates the virtual machine for any OS capable of running Java.

Summary
The changing mobile landscape requires a web content management system able to creatively address the problems of modern websites. Drupal is just such a CMS. I stated it earlier in the chapter, but it bears repeating—Drupal's worldwide developer base ensures that any problem you ever attempt to solve has been solved by multiple other developers in several different contexts.
The first task at hand is to set up a mobile simulator so we can view web pages as they appear on the device. We did that by installing an Android simulation environment on Windows and XCode from Apple's Mac App Store.
In the next chapter, we will take a look at our example site and get a sane development environment in which we'll build this fantastic mobile site.
We're going to outline a workflow that will allow developers in teams to work with Drupal in a way that allows everyone to do their jobs without stepping on anyone's feet, and at the same time, minimizing the amount of overhead work any developer needs to do. Ready to go? Let's get started!



jQuery Fundamentals - Getting Started



You probably spend more time in front of a computer than with your signifi cant other. Hence, having a nice comfortable seat, a fast computer, and software that accelerates development is essential.
Starting with the basics, we’ll review requirements, different ways to obtain jQuery, and how to run it on both client and server, and set up some conventions for the rest of the book, using Google’s JavaScript standards.
In this chapter you set up your work environment for developing and debugging jQuery and JavaScript code. A major portion of development time goes into debugging, so a good debugger isn’t really an option. After reviewing Firebug, Chrome, and IE debuggers a portion of this chapter covers debugging JSON, tools for inspecting HTTP headers, and the JSLint code quality tool.
You learn to package your .js fi les for production use, explore tools, and establish some coding conventions.

WHAT JQUERY IS GOOD AT
Without a doubt, one of the strong points of using jQuery is how it diminishes many crossbrowser concerns. Without it, writing cross-browser-compatible JavaScript code is a tedious, and unnecessary, exercise. It’s diffi cult not to marvel at how much time is saved getting things running in both IE and Firefox with jQuery. The core is also excellent at traversing the DOM tree and selecting elements. It’s also very lightweight, with the production version standing at 29 kb, which is minifi ed and compressed. That’s a lot of kick for a small fi le. When debugging and testing, you’re better off using the uncompressed development version, which is 212 kb. jQuery is also good at handling fairly complex JavaScript code with relatively little code. This was one of my initial attractions to the framework. For a newbie trying to learn the “ropes” with Ajax, jQuery lowers the learning curve. Understanding what’s going on under the hood is important, but as a fi rst step, using $.ajax() isn’t a bad start.
An active user community means active support. Googling jQuery returns about 36.8 million results at the time of this writing. New offi cial and third-party plugins come out every day, extending its core functionality. With so many projects dependent upon jQuery, it’s easy to fi nd help online (and really cool print books too). With that said, it might be overkill in some cases. Remember that including the jQuery library has some overhead, even if it’s small, and if you’re only using the selectors to get an element by its ID, then the built-in JavaScript capability of the browser is enough. But, if you plan to build a featurerich, dynamic Ajax web application, jQuery is the way to go.
 
HARDWARE AND BROWSER REQUIREMENTS
Your requirements for running jQuery are very light: a computer, smart phone, or device capable of running a modern browser. The browser requirements are fairly liberal as well. The offi cial site lists the following browsers that are supported as well:
 
·         Firefox 3.0+
·        Internet Explorer 7+
·         Safari 3+
·         Opera 10.6+
·        Chrome 8+


The following browsers are known to give problems:
·        Mozilla Firefox 1.0.x
·         Internet Explorer 1.0–5.x
·        Safari 1.0–2.0.1
·        Opera 1.0–9.x
·        Konqueror
Quirksmode has a great page detailing the CSS compatibilities of different browsers, including CSS3. To fi nd out more visit www.quirksmode.org/css/contents.html.

OBTAINING JQUERY AND JQUERY UI
Besides the links found on jquery.com for downloading the production and development versions, you have a few other options for obtaining or linking to the jQuery libraries. You can link to several content delivery networks (CDNs) in your applications such as Google, Microsoft, and the jQuery CDN that are mentioned on the offi cial jQuery website.
The following code illustrates obtaining jQuery from the various available CDNs. Simply add a script tag, point it at the proper URL and you’re ready to go.
 
<script src=”https://googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”></script>
<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js”></script>
<script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>

 
Code snippet is from cdns.txt
A Git repository also hosts a “Work in Progress,” or WIP, build. This is a constantly revised development version, which is not meant for production. The WIP build is generated every minute.
To use this bleeding-edge version you can directly link from http://code.jquery.com/jquerygit. js or you can clone the Git repository to build jQuery from scratch. The following code shows the Git command used to clone the latest version of the library.

$ git clone https://github.com/jquery/jquery.git jquery-build
In order to build, you’ll need GNU to make 3.8+ and Node.js .2+. After cloning the repo, change into the jQuery directory and execute the make command. This will generate a complete minifi ed version of jQuery, and run through JSLint (more on JSLint later). If you don’t want this, run make jquery instead of make.

“HELLO WORLD” EXAMPLE
No programming text is complete without the ubiquitous “Hello World” program:

<html>
<head>
<script
src=” https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js”>
</script>
<script
jQuery(document).ready(function(){
alert(‘Hello World’);
});
</script>
</head>
<body>
</body>
</html>
 In a nutshell, a minifi ed version of jQuery is loaded from an online CDN over the Web. The jQuery function is called with the document object passed in as a parameter. This creates a jQuery wrapper object which has a ready() method whose only argument is a function. This function is invoked when the browser has fi nished converting the HTML on the page into the document object model (or DOM). At that moment, your function displays an alert, “Hello World.” There’s much more going on here than meets the eye and if you don’t understand yet, don’t worry. Chapter 2 revisits JavaScript, and most importantly, JavaScript’s way of managing functions. There you’ll understand the reason for the anonymous function. In Chapters 3 and 4, you see the concepts behind the jQuery wrapper, and using selectors to get elements from the DOM. Then you’ll have a better idea of what jQuery(document) means. Finally, in Chapter 5 you get acquainted with event handling, such as the aforementioned .ready(). So, although the code written for this example is rather brief, it’s rather dense and will be unpacked later.
 
JAVASCRIPT CONVENTIONS USED IN THIS BOOK
Throughout this book, we’ll stick to a small subset of the Google JavaScript Style Guide found at http://google-styleguide.com/svn/trunk/javascriptguide.xml and the jQuery Core Style Guidelines found at http://docs.jquery.com/jQuery_Core_Style_Guidelines. The Google JavaScript Style Guide specifi es the following:
 
·        Declarations of variables always use var, except when intentionally creating a global variable.
·        Always use semicolons. This is important for minifying code.
·        Constants are uppercase, with each word separated by an underscore.
·        Functions, variables, and method names all use camel case notation with the fi rst letter lowercase.
·        Classes and enum names also use camel case notation but with the fi rst letter uppercase.
 
The big exception to any of these rules is when an example demonstrates how not to do something. The jQuery team also published a set of conventions for development of the core library. The documentation mentions the following:
 
·        Spacing code: Abundantly use spacing, using tabs to indent code. Don’t use white spaces at the end of lines and empty lines should not have spaces either. This example illustrates the preferred spacing.

if ( test === “test string” ) {
methodCall( “see”, “our”, “spacing” );
}
·        Using comments: For multiple-line comments use /* */ and for single-line comments use //, with an empty line above the comment. The single-line comment precedes the comment that it refers to, and should be the only thing on the line.

// my comment
var x = ‘blah’;
var x = ’blah’; // bad
·         Equality: Always use identity (===) comparison over simple quality (==). The jQuery team makes the exception of using simple equality when testing for null. As the guidelines say, “It’s actually quite useful to do == null or != null as it will pass (or fail) if the value is either
null or undefi ned.”
·        Block presentation: Always use braces for control constructs (if/else/for/while/try), and distribute over multiple lines. Don’t use the one liner ifs without braces. Braces should always be placed on the same line as else/else if/catch. It’s also suggested to avoid replacing if/else statements with ternary operators. Here are some examples:
 
// bad
if( stuffHappens ) alert(‘blaaaah’);
// good
if( stuffHappens ) {
alert(‘blaaaah’);
}
// also good
if( option ) {
// code here
} else {
// code here
}
·        Function call format: Include extra spaces around function call arguments with the exception of when a function call is nested, a function call is empty, or object literals and arrays are passed:
 
// These are OK
f( arg );
f( g(arg) );
f();
f({ });
f([ ]);
·        Arrays and objects: No extra spacing is preferred for empty object and array literals, but do use a space after commas and colons:

var a = {};
var b = [];
var c = [ 1, 2, 3 ];
·        Assigning variables/objects: Always use a semicolon at the end of assignments with an endline afterwards. As noted by the Google Style Guide, semicolons should always be used.
·         Type checks: Table 1-1 demonstrates what strings to use when doing a type check.

TABLE 1-1: Type Checks
OBJECT
TYPE CHECK EXPRESSION
String
Number
Boolean
Object
Element
null
null or undefined
typeof object = = =“string”
typeof object = = = “number”
typeof object = = = “boolean”
typeof object = = = “object”
object.nodeType
object = = = null
object = = null

Table 1-2 illustrates objects that are type checked using the jQuery API.
 
TABLE 1-2: Type Checks Using the jQuery API
OBJECT
JQUERY METHOD TO USE FOR TYPE CHECKING
Plain Object
Function
Array
jQuery.isPlainObject(object)
jQuery.isFunction(object)
jQuery.isArray(object)

 

Table 1-3 illustrates methods for type checking undefined.
 
TABLE 1-3: Checking undefined
OBJECT
.
Global Variables
Local Variables
Properties
typeof variable = = = “undefined”
variable = = = undefined
object.prop === undefined

·         RegExp: Create regular expressions (RegExp) with .text() .exec().
·        Strings: Double quotes are preferred to single quotes.
The docs also mention validations with JSLint. JSLint is covered in the next section on Development Tools.
There are differences between the Google JavaScript Style Guide and jQuery’s Style Guide.
For example, the Google JavaScript Style Guide suggests the use of single quotes, whereas the jQuery team uses double quotes as a standard. For this book, we stick to the jQuery team’s suggestion.

DEVELOPMENT TOOLS
You have several tools at your disposal for developing JavaScript and jQuery, other than the traditional editor/browser setup. If your style of development is more command-line-oriented, you have jconsole and Rhino. jconsole is a web application that enables you to interactively enter JavaScript code. It comes with a few additional functions such as print(), load(), and clear(). Multiple line entries are allowed by pressing Ctrl+Enter after each line. Pressing Enter executes the current code in the text area. jconsole also maintains a history of entered commands, which is accessed by pressing the up or down arrows to use the previous and next entered commands.
Figure 1-1 shows jconsole in action.


FIGURE 1-1

To load jQuery into jconsole use the load() function with a CDN URL. For example:
·        load(‘https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js’);
$(document).click(function(){ alert(‘It worked!’); });
jconsole also has a tab autocompletion feature, and the ability to dynamically change the execution context by entering the scope() function. For quickly testing small bits of code, jconsole really is priceless.
You probably picked up this book for using jQuery in a browser environment, but it’s also possible to use jQuery on the server. Mozilla Rhino is a JavaScript interpreter implemented in Java. It’s commonly used to embed JavaScript into Java applications. It features a JavaScript shell, debugger, and compiler. Along with the framework Envjs, also written by the jQuery creator John Resig, it’s possible to use jQuery in a server environment. Envjs is a portable JavaScript implementation of a “headless browser,” or browser that lacks a user interface that provides a scripting environment.
It’s possible to get the same effect with other host environments, such as Google V8, but I’ll stick to Rhino for this example.

Table 1-4 lists the dependencies for getting up and running with jQuery and Rhino.

DEPENDENCY
FUNCTIONALITY
Rhino
JLine(optional, but
useful)
Envjs
Command-line JavaScript interpreter
Java console input library, readline-like functionality

“Headless browser,” scripting environment

To get readline-like functionality, run Rhino with the JLine library. This way you can access the history of commands by pressing the up arrow, and edit entered characters with left and right arrow keys. The following code block shows how to get started with JLine. java -cp js.jar:jline.jar jline.ConsoleRunner \org.mozilla.javascript.tools.shell.Main -opt -1
The following session demonstrates how to get jQuery running with Rhino. Lines with js> indicate input.

js> load(‘env.rhino.1.2.js’);
[ Envjs/1.6 (Rhino; U; Linux i386 2.6.24-25-generic; en-US; rv:1.7.0.rc2)
Resig/20070309
PilotFish/1.2.13 ]
js> window.location = “http://localhost”
http://localhost
js> load(‘jquery.js’);
js> jQuery
function (selector, context) {
return new jQuery.fn.init(selector, context);
}
Back in the regular browser world, Firefox also has plugins for simplifying your life as a developer. One of the most popular is Firebug, a debugging tool for web development. Firebug enables live editing of HTML and CSS, debugging, and monitoring of web applications. Figure 1-2 shows the Firebug interface.

FIGURE 1-2

To install Firebug, go to Tools Add Ons on the menu bar, click Get Add Ons on the resulting dialog, and search for Firebug. Click Add to Firefox. After installing, you’ll notice a bug icon at the bottom right of the window. Click it to open the Firebug explorer. You’ll notice Firebug includes six tabs: Console, HTML, CSS, Script, DOM, and .NET. Each tab contains features to simplify your life as a web developer.
The Console tab provides an output interface for viewing warning and error messages, logs, debugging information, general info, and XmlHttp Request and response objects. Firebug loads into the global namespace an object called console. Use this object to log console messages of the inner workings of your application. The console object contains several methods, which you can check out at http://getfirebug.com/wiki/index.php/Console_API . Table 1-5 lists a small subset of the methods contained by the console object with descriptions provided by the Firebug Wiki.
The profi ler is used for performance analysis of your application. Profi ling is as simple as clicking a button. Load your page, click the Profi le button under the Console tab, use your application for a while, and click the Profi le button again to generate a report.
The HTML tab enables you to peruse the DOM and edit HTML code “on the fl y.” The tags are displayed in a tree widget, which expands to show the children of each node. The CSS tab also enables editing of styles and layout, while neatly displaying the values of each cascading style sheet. Perhaps one of Firebug’s most useful features is the interactive command line, which allows execution of JavaScript code in the context of the web page you’re developing. There’s no need to manually load jQuery and other dependencies. The console also has command completion. The Script tab also has the ability to add/remove breakpoints, view stack traces, and watch variable values over time.
It’s also possible to use Firebug with other browsers via Firebug Lite. To do so, include in your HTML fi le a script tag that links to the .js fi le online:

<script src=”https://getfirebug.com/firebug-lite.js”></script>
Along with Firebug, Live HTTP Headers, another Firefox plugin, gives a nice rounded view of the data fl owing in and about your application. The “Live” means that the HTTP header information is displayed in real time.
To install, follow the same procedure you used for Firebug. After installing, you can access Live HTTP Headers from the menu bar by selecting Tools Live HTTP Headers.
A dialog displays the get requests with all kinds of useful debug information such as server type, encoding type, cookies, host, and so on. The replay feature enables you to edit request headers and resend a URL, great for debugging Ajax.
When trying to load JSON data directly from Firefox, the default behavior of the browser is to give you a Download File dialog. Using the JSONView extension Firefox will interpret and display JSON data in a nice legible manner. Furthermore, the nodes are collapsible, similar to when Firefox interprets XML data directly. For example, say you have the following .json fi le:

{
“users”: {
“user”: [{
“name”:”Tom”,
“email”:”tom@bigcorp.com”,
“role”:”admin”
},
{
“name”:”Nick”,
“email”:”nick@bigcorp.com”,
“role”:”employee”
},
{
“name”:”Lynn”,
“email”:”lynn@bigcorp.com”,
“role”:”manager”
},
{
“name”:”Carol”,
“email”:”carol@bigcorp.com”,
“role”:”manager”
}]
}
}
            With JSONView, the output should look similar to the following code snippet. The minus sign indicates a collapsible node, and a plus sign indicates an already collapsed node. The last two records are collapsed.

{
- users: {
- user: [
- {
name: “Tom”,
email: “tom@bigcorp.com”,
role: “admin”
},
- {
name: “Nick”,
email: “nick@bigcorp.com”,
role: “admin”
},
+ { … },
+ { … }
]
}
}name: “Lynn”email: “lynn@bigcorp.com”
role: “manager”
Google Chrome also offers a top-notch development environment. A set of developer tools comes by default with Chrome. These are in active development, so the feature set is constantly evolving and improving. The Chrome Developer Tools come with all the same goodies as Firebug: an interactive command line, element inspector, the ability to add/remove breakpoints, and so on. To access the developer tools press Shift+Ctrl+I.
Figure 1-3 shows the Chrome Developer Tools.


FIGURE 1-3

 Another essential tool is JSLint, the “JavaScript code quality tool,” which checks and validates code. Douglas Crockford explains it best: “JSLint takes a JavaScript source and scans it. If it fi nds a problem, it returns a message describing the problem and an approximate location within the source.” Just like jconsole, there’s a convenient web application for validating your JavaScript code; see www.jslint.com. Optionally, clone the source from Github at https://github.com/ douglascrockford/JSLint.git. In the source code you’ll fi nd fulljslint.js, which you can run outside of a web browser. Using Mozilla Rhino, you can use a short script for validating JavaScript/ jQuery code from a command line.

load(‘JSLint/fulljslint.js’);
var src = readFile(arguments[0]);
var passes = JSLINT(src);
print(passes ? ‘Passes Lint Validation’ : ‘Failed Validation’);
The functions load(), readFile(), and print() are Rhino-specifi c functions. The load() function takes the input string pointing to the fulljslint.js fi le, loads the code into memory, and executes it giving you access to the JSLINT() function. The readFile() function obtains the fi rst parameter passed in from the command line, using the arguments array, and reads the source into a string. The JSLINT() function then validates the content of the src variable, and returns a Boolean object signaling whether or not the string validated. With a ternary operator a message is then printed to the console depending on whether the fi le read passed validation. Open a terminal, and try validating a simple JavaScript fi le:

$ rhino runLint.js test.js
Passes Lint Validation
If the above seems like too much work, you can also take a look at the project, jslint4java at http://code.google.com/p/jslint4java/ , which simplifi es the command to the single line seen in the following code snippet.

$ java -jar jslint4java-1.4.jar test.js
 In addition to JSLint, there’s an alternative code quality tool that’s gaining popularity, JSHint www.jshint.com/ . Originally forked from JSLint in order to create a more confi gurable version of JSLint that didn’t enforce one particular coding style, JSHint has grown into a project of its own, with its own goals and ideals. If you fi nd yourself running up against specifi c, non-confi gurable rules in JSLint or merely want to try out an alternative then JSHint might be a good option for you.
Finally, after fi nishing development of any modules or plugins, and validating using JSLint, you’ll probably want to minify your .js fi les for production. Several options are available on the market, but I’ll just discuss a few. Some popular open source options are the YUI Compressor, the Google Closure Compiler, UglifyJS, and JSMin. YUI Compressor offers the additional ability to minify CSS alongside your JS. While it is convenient to have one-stop shopping for all of your minifi cation needs, the two dominant choices right now are UglifyJS, a NodeJS-based utility, and Google’s Closure Compiler. Both are in use at major JavaScript performance-obsessed projects. UglifyJS is the minifi er of choice for the jQuery project itself and the Java-based Closure Compiler is the minifi cation choice for HTML5 Boilerplate http://html5boilerplate.com. Both can be run from the command line, which allows you to automate this minifi cation process alongside any JSLint tests you may also be running. The HTML5 Boilerplate project offers a full-featured Ant build script which does both minifi cation and JSLint or JSHint tests (and more).
If you’re interested in getting your hands dirty, the following code samples show how easy it is to run both UglifyJS and Closure Compiler from the command line. Assuming you’re running NodeJS, installing UglifyJS is as simple as the following:

npm install -g uglify-js
Running it is as simple as calling UglifyJS, setting the -o (output) fl ag, and setting an output fi lename and passing in the input fi lename to be mininfi ed:

uglifyjs -o app.min.js app.js
Using Closure Compiler is also very simple. Simply download the latest jar from http://closurecompiler.googlecode.com/files/compiler-latest.zip , unzip it and then run the following from the command line. It follows a similar pattern with an input fi le and an output fi le provided as command line arguments.

java -jar compiler.jar --js app.js --js_output_file app.min.js
If you aren’t a guru, or don’t understand how to use a command line, don’t sweat it. There are the web-based applications to get the same results.

DEBUGGING JAVASCRIPT AND JQUERY
It’s time to use the tools discussed in this chapter, especially Firebug (or the Chrome developer tools) and JSLint - they’ll catch many errors for you. Rather than using alert calls with variables and objects, place breakpoints and inspect the values of each object/variable as they are manipulated by your scripts. Also, make liberal use of the real-time editing.
Separating markup from functionality is the way of modern web development, for many reasons. One reason for keeping your JavaScript/jQuery code in an external .js fi le is that it helps the debugger correctly match the error with the actual line number, not to mention it keeps your code unobtrusive.
Make your projects test driven. Later in the book, I describe how to use QUnit to add unit tests to your projects. As you probably already know, although jQuery handles most cross-browser concerns, it’s still necessary to test in different browsers and environments, including portable devices like iPhones. Having a full test suite will make it easier to detect and squash cross-browser bugs.
For small bits of code, like one-liners, use console applications like jconsole and Rhino to make sure you’re getting the expected results.
Make sure of the obvious. The most experienced programmer may miss something obvious. Who hasn’t added a script tag for including jQuery, only to fi nd out much later, to great dismay, that the path was mistyped? The debuggers will let you know quickly if the $ variable is undefi ned.
Being aware of browser-specifi c issues and their particular behaviors is important. That trailing comma in an object literal is just priceless after you’ve developed in a browser like Firefox or Safari for hours, only to have your beautifully scripted project explode in IE.
One point we mention time and again in this book is the necessity to really grok JavaScript. The learning curve for jQuery is low; it’s a wonderful framework for beginners to create dazzling JavaScript effects. However, advanced users doing full development shouldn’t treat it as a black box.
It embraces and extends JavaScript, and thus requires JavaScript understanding.
Of course, there are all the other regular tips as well. For example, make sure your HTML and XML are well formed, use version control tools like Mercurial or Git, and call on the Google orStack overfl ow gods when you’re really stuck.

USING THE FIREQUERY PLUGIN
There’s another Firefox plugin for your jQuery repertoire: the FireQuery plugin, which enhances Firebug for better handling of jQuery. Features include:
·        Elements and handlers dynamically added by jQuery at run time can be visually inspected in the console.
·        Elements that are members of a jQuery “collection” are highlighted in the window on a mouseover event.
·        jQuery-specifi c expressions are recognized and presented in the Firebug console.
 
One of its more interesting features is the “jQuerify” button, which dynamically loads jQuery into any web page viewed by the browser. This is very useful if you’re running tests with jconsole, because it cuts out the step of loading jQuery from a CDN using the load() command in the console. After you install FireQuery, you can check that everything is working correctly by visiting the test page at http://firequery.binaryage.com/test/index.html . Figure 1-4 shows a successful install of FireQuery.

FIGURE 1-4

SUMMARY
In this chapter you explored a couple of different options for obtaining, building, and running jQuery. Not only that, but you know now how to run JavaScript code from the server, instead of just the traditional browser client. After you’ve learned to develop your own jQuery plugins, you can use the techniques in this chapter to minify and prepare your code for deployment to a larger audience. You’ve also sipped a taste of the many debugging tools out there.
In the following chapter you go full blast into coding, and put all these tools to use, but our focus is more toward general JavaScript before getting back to jQuery-focused code.