1. Introducing jQuery

Rich, interactive Web sites that use semantic markup and unobtrusive technologies like Cascading Style Sheets (CSS) and JavaScript are becoming the de facto standard in Web development. Designers and developers are looking for new and better ways to bring their creations to life, and libraries like jQuery make this goal easily attainable.

To get started properly with jQuery, you need to equip yourself with the appropriate tools and concepts. So, I’ve gathered those tools for you and will help you to learn how to use them.

This chapter will give you a firm grasp of the basics of jQuery and the tools that will make working with jQuery straightforward. Also included are some tips for getting the most out of jQuery. But first things first; let’s start with a “Hello World” example jQuery style.

MAKING jQUERY WORK

The strength of the jQuery library is its ability to interact with elements in your Web pages that you are already familiar with. Markup tags, class declarations, and attribute information in your Web pages can be easily connected to jQuery by using the simple concept of selectors.

A jQuery selector will wrap an element or set of elements into an object. Once you have created the jQuery object, you can effectively apply a multitude of jQuery methods to that object to create animations, send information to and from the server, or perform object manipulation.

No book on programming is worth its salt if it doesn’t have a “Hello World!” example. To illustrate the power and flexibility of jQuery’s selectors, let’s create a “Hello World!” example.


Note

The Hello World code is the only code example not available in the download from the book’s Web site. The reason is that I think it is very important that you type this one in yourself. Comments are also included in the example.


1. Start by establishing the basic markup for the HTML page:

<!DOCTYPE>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Hello World - jQuery Style</title>

2. Be sure to include the jQuery source file. Without this file none of the jQuery code will operate:

        <script type="text/javascript"
        Image src="jquery-1.5.min.js"></script>

3. Open a script tag to give the jQuery code a place to live within the page:

        <script type="text/javascript">

4. The jQuery functions that you are creating need to be available to run after the Web page has finished loading all of its elements. To accomplish this, you wrap the jQuery code in a document ready function. Just as it implies, the code wrapped in the function becomes available to run when the Web document is ready:

        $(document).ready(function() {

5. Create the first selector. This selector will get the markup element in the page having an id attribute equal to first. All id attributes are selected in jQuery (and CSS) by prepending the hash (#) sign to the information contained within the id attribute. You’ll follow the selector with jQuery’s html method by chaining the html method to the selector. This method will place the markup <h1>Hello World!</h1> into the selected element:

            /* write 'Hello World! to the first div */
            $('#first').html('<h1>Hello World!</h1>'),

Chaining is the term used to describe applying one or more methods to jQuery objects. Chaining gives you a wide variety of possibilities to combine methods to create unique interactions for your Web-site visitors.

6. For this example, you’ll create one additional method that connects, or binds, an event handler to a selector to create an action. The event handler will accept an action and perform additional jQuery functions to other selected elements. Start this portion of the example by binding jQuery’s click handler to an element with an id of link:

            /* a clickable 'Hello World!' example */
            $('#link').click(function() {

The click method exposes a handler function that allows you to build a string of actions that will be triggered by the click method.

7. Set up a selector for the element with an id of greeting and apply the html method to it:

                $('#greeting').html('<h1>Hello Again!</h1>'),

8. Close out the jQuery code with the proper braces, brackets, and script tags:

            });
        });
        </script>

Pay close attention to braces and brackets when you create jQuery code. It is critically important that each opening bracket or brace have a matching closing bracket or brace.

9. Finish up the head section of the markup and open the body of the Web page:

    </head>
    <body>

10. Create an HTML div with an id of first. The initial jQuery selector that you created previously will interact with this element, adding the HTML markup that was specified between the div tags:

        <div id="first"></div>

11. Create another HTML div with an id of second. You did not write any selectors for this element; it is just being used as a container for other elements:

        <div id="second">

12. Create an anchor tag and give it an id of link. You wrote jQuery code earlier that will handle the link when it is clicked by a user:

            <a href="#" id="link">Click Me!</a><br />

13. Create a span element with an id of greeting. When the link is clicked, the selector for greeting will apply the HTML markup you specified between the span tags:

        <span id="greeting"></span>

14. Complete the page by closing out the markup tags properly:

        </div>
    </body>
</html>

Figure 1.1. The “Hello World!” message appears when the page loads, and the “Hello Again!” message appears when the link is clicked.

Image

15. Save the file as hello_world.html and load it into your Web browser. If you have been diligent with your typing, you will be rewarded with a Web page identical to the one shown in Figure 1.1.

This example is just a small taste of how you can connect jQuery to elements in your Web pages to provide information and interactivity. The example also demonstrates how you can add elements to your Web pages using jQuery.

To work with jQuery effectively, you need to know how to work with all of the elements in a Web page and how they are assembled into a document.

A document?

That is absolutely correct: Web pages are documents that are intended for display in Web browsers. Because Web pages are documents, they follow some of the same rules that paper documents follow, and those rules are provided by the master document—the Document Object Model (DOM).

WORKING WITH THE DOM

Figure 1.2. Examining the DOM using Firebug with Firefox.

Image

At the heart of all of your Web pages is an API (Application Programming Interface) that describes everything on the page. It is the DOM. The DOM provides information for each element on the page, including styles associated with elements. The information in the DOM is stored in a tree-like structure.

Several DOM inspector applications are available either as stand-alone applications or as add-ins to many popular Web browsers. Figure 1.2 shows the DOM inspector available with Firebug.

Figure 1.3. An outline of the relationships between the elements in the list.

Image

The DOM API is what allows languages like JavaScript and libraries like jQuery to interact with elements in your Web pages. You can use libraries like jQuery to virtually climb up and down the DOM tree to locate, add, remove, and modify elements. Because you’ll be using jQuery to interact with the DOM, including adding and removing elements from it, you need to become familiar with how the DOM is constructed. You don’t need to become an expert on the DOM, but you should know enough about the DOM to recognize what is going on when you manipulate it with jQuery.

Knowing the DOM becomes critically important when you start working with jQuery’s parent and child type selectors. You must understand the relationship between the elements in the DOM so that you can effectively manipulate those elements. Consider the following HTML markup:

<div id="information">
    <ul>
        <li><a href="foo.html"><img src="bar.jpg" /></a></li>
        <li><a href="glorp.html"><img src="murkle.jpg" /></a></li>
    </ul>
</div>

To know how to travel up and down the DOM tree, you must know what the relationships are between the elements. Figure 1.3 shows how those relationships are defined.

Armed with this knowledge, you can traverse the DOM elements for this list. Given that you know the image source in the first list item, you can retrieve the source attribute from the second image in the list easily, like this:

var nextImage = $('img[src="bar.jpg"]') // define the starting point
    .closest('li') // travel up to the closest list item
    .next() // move to the next list item
    .find('img') // find the image tag in the next list item
    .attr('src'), // grab the sounrce attribute of the found
    Image image tag

The variable nextImage now contains the value murkle.jpg.

LEARNING A FEW jQUERY TIPS

As I use and continue to learn more about the jQuery library, I’ve accumulated some good rules of thumb, including being specific about jQuery selectors, caching selectors, and packing up code to make it more efficient. These and other tips provided here will make your code more effective, provide you with some good tools, and shorten your development time.

SELECTING ELEMENTS SPECIFICALLY

To find the elements that you want to act on, jQuery has to traverse the DOM tree. Depending on the length and complexity of a page, the DOM can be quite large. Using grossly formed selectors can slow performance and lead to frustration.

jQuery reads selectors right to left, so if you have a selector like this:

$("div ul li a");

jQuery will gather all the anchors first, determine if they are within list items, and then find out if the list item is contained within an unordered list that is contained within a <div>.

Whew! It would be better to give one group of these items a class or an id attribute that will allow you to more directly identify one or more of the elements involved. For instance, the anchor tags in this group can be navigation elements and given a class of navigation (<a href="nav1.html" class="navigation">). That will allow you to shorten the selector to $(".navigation"). As an added bonus, the element can be more easily referred to and styled in CSS!


Tip

Thanks go out to the very supportive jQuery community for the tips included in this section. You can learn a lot by participating in the jQuery forums at http://forum.jquery.com. Forum participants are always willing to lend a hand to help you solve your jQuery and JavaScript problems.


MAKING QUICK WORK OF DOM TRAVERSAL

Sometimes, you might need to upgrade a poorly planned older site or application that was developed by someone else. The selector mentioned in the previous section, $("div ul li a"), might have to be used repeatedly to achieve the results that you are trying to apply with jQuery. If that is the case, you should cache the selector so that you only need to traverse the DOM once for that selector:

var myNavLinks = $("div ul li a"); // perform the traversal and
Image stores it
$(myNavLinks) // the new selector doesn't have to traverse the
Image tree again

Caching becomes a valuable performance tool when you want to manipulate dozens or maybe even hundreds of table rows and cells.

TROUBLESHOOTING WITH FIREBUG

Available for nearly every browser, Firebug is the leading tool for debugging and profiling JavaScript. It should definitely be in your Web development toolbox.

Firebug allows you to carry out several tasks, including watching your code “in action” to see how it behaves when events are triggered on your Web pages. For instance, in Figure 1.4 a link has been clicked. If you look closely, you can see that several lines of HTML have been highlighted in yellow. Those lines are the portion of the HTML affected by the clicked link.

One of Firebug’s handier features is its ability to identify JavaScript (and therefore jQuery) errors accurately, allowing you to quickly troubleshoot and correct problems.

I’ll use some of Firebug’s features throughout the book. To talk about and demonstrate all the features Firebug has to offer would take an entire book!


Tip

Firebug is a free download from http://getfirebug.com.


Figure 1.4. Using Firebug, you can examine jQuery’s actions.

Image

PACKING UP YOUR CODE

While you are working on writing your code, it helps to use lots of white space and comments. All of the comments and white space take up room, so it is best to pack up your code when you get ready to move your code into production. You may have noticed that the official jQuery site, as well as plugin developers, offer scripts in two versions: a normal version and a minified version. The minified version strips out most of the white space and comments. This ensures that your Web site is delivered more efficiently.

Several tools are available for packing up your code. One of my favorites is a freebie provided by Google, the Google Closure Compiler (http://code.google.com/closure/compiler). Google’s Closure Compiler provides a quick method for minifying your code and offers some additional advantages like checking for illegal JavaScript.

For fun, let’s pack some code in the file spritenav.js, which you will use later in the book. With white space and comments, the code looks like this:

/*
 * NAME: SpriteNav(jQuery)
 * AUTHOR: Jay Blanchard
 * DATE: 2011-01-10
 * BUSINESS RULE:    <if applicable>
 *
 * REVISION:    a20110110jb
 * STATUS:      open

 * USAGE:       call from web interface page                                                        
 *
 * REVISION HISTORY
 *
 * a20110110jb   - create CSS and XHTML for initial testing layout
 *
 */
$(document).ready(function() {

$(function() {
    /* set original values */
    $("#spriteNav span").css("opacity", "0");
    $("#spriteNav span.selected").css("opacity", "1");

    /* how do we hover? let me count the ways... */
    $("#spriteNav span").hover(function() {
        if($(this).attr("class").length == 0) {
            $(this).stop().animate({
                opacity: 1
            }, 75); // end mousein
        } else {
            $(this).css("opacity", "1"); // end mousein
        }; //end if
    }, function(){
        if($(this).attr("class").length == 0) {
            $(this).stop().animate({
                opacity: 0
        }, 250); // end mouseout
    } else {
        $(this).css("opacity", "1"); // end mouseout
    }; //end if
}); // end hover function
        
    /* click me! click me! */
        $("#spriteNav span").click(function() {
            /* we clicked, so remove the selected class from all */
            $("#spriteNav span").removeClass("selected");
            /* then add it to the selected one */
            $(this).addClass("selected");
            /* then fade out the previously selected item */
            /* be specific about the ones to be faded out */
            $("#spriteNav span:not(.selected)").stop().animate({
                opacity: 0
            }, 500);               
        }); // end click function
    }); // end function
}); // end document ready function

Figure 1.5. The code before and then after packing, which also reveals warnings and errors that are encountered by the Closure Compiler.

Image

In Figure 1.5 you can see the side-by-side comparison of the code before and after packing. After packing the code with the Google Closure Compiler, it becomes:

$(document).ready(function(){$(function(){$("#spriteNav span").css
Image ("opacity","0");$("#spriteNav span.selected").css("opacity",
Image "1");$("#spriteNav span").hover(function(){if($(this).attr
Image ("class").length==0){$(this).stop().animate({opacity:1},75)}
Image else{$(this).css("opacity","1")}},function(){if($(this).
Image attr("class").length==0){$(this).stop().animate({opacity:0},
Image 250)}else{$(this).css("opacity","1")}});$("#spriteNav span").
Image click(function(){$("#spriteNav span").removeClass("selected");
Image $(this).addClass("selected");$("#spriteNav span:not(.selected)").
Image stop().animate({opacity:0},500)})})});

Reduced to 40 percent of its original size (1360 bytes originally; 567 bytes after minifying), the code is very compact.

Although this is a good example of the gains to be made while minifying jQuery code, you really don’t need to minify small files. If you are using a number of small files, it is best to combine them and then run them through the reduction process. If you plan to minify your files, be sure to keep one copy that you use for editing with all the white space and comments intact, and then minify when you are ready to use the file on a production Web site or application.

USING RETURN FALSE

Anyone who has done any amount of JavaScript programming, including programming with jQuery, has run into return false;. For the most part, many have used it improperly. Let’s look at an example, an HTML anchor tag link:

<div><a href="inc/content.html">Click Here!</a></div>

Typically, you might apply something similar to the following jQuery to handle the anchor tag:

$("div a").click(function() {
    var link = $(this).attr("href");
    $("#content").load(link);
    return false;
});

In this example you want to be able to click the link and have that link not perform as it normally would; you want it to just load the information from the link into the element with an id of content. So, you insert return false; into the function. It works! But do you really know how?

Because return false works so well, you may not realize when it trips you up later on. The return false function first calls preventDefault(); and then it calls stopPropogation(). The function stopPropogation() stops the click event in this case from bubbling up the DOM, which may prevent subsequent click events from working on the ancestors you may add later. You’ll end up scratching your head a lot when your seemingly perfect code fails to do what you ask of it with no errors lurking about to give you a clue as to what happened.

More often than not what you should use is preventDefault(), as shown in the following highlighted code:

$("div a").click(function(e) {
    var link = $(this).attr("href");
    $("#content").load(link);
    e.preventDefault();
});

Take a few minutes to become familiar with the other related functions, stopPropogation() and stopImmediatePropogation(), because you may find them handy and revealing!

FIDDLING WITH jQUERY CODE

One of the most useful and coolest tools I’ve seen in many years is a Web application called jsFiddle (http://jsFiddle.net). Developed by Piotr Zalewa as “a playground for Web developers,” jsFiddle is a great Web site where you can combine HTML and CSS while experimenting on that code with jQuery (Figure 1.6). The tool supports several different versions of jQuery and is an excellent troubleshooting tool.

Using the jsFiddle Web site is a great way to share code with other developers for discussion, troubleshooting, or bragging rights. The Web site also allows you to include the latest jQuery UI (user interface) code in your experiments.

Figure 1.6. Using jsFiddle, you can test a jQuery code snippet.

Image

COMBINING jQUERY WITH OTHER CODE

Throughout the book, you’ll be using several technologies to bring your Web applications to life. To start, you’ll use HTML, CSS, and JavaScript, and then mix in PHP and MySQL to support further interaction.

STARTING WITH HTML

HTML is what you’ll use to start all of your Web pages. Use of the latest version of HTML, HTML5, is on the rise, and examples in the book use it where appropriate. Because HTML5 is still in development, browser support is limited. I recommend plenty of cross-browser testing when using HTML5.

jQuery can select HTML DOM elements easily. For instance, if you have a form input element:

<input name="username" type="text" size="48" />

you can use the jQuery selector $('input[name="username"]') to interact with the element.

STYLING WEB PAGES WITH CSS

CSS can be tricky territory because different browsers provide different levels of support for the properties that CSS has to offer. Cross-browser testing is still required to make sure that what displays in one also displays in another. It is very important to understand that it is OK if your sites do not look exactly the same from browser to browser.

jQuery will support the latest and greatest CSS version, CSS3, and all of its properties, but make sure that you test in many browsers because that is the only way you can determine if what you see is acceptable to you.

USING PHP AND MYSQL

As one of the most popular server-side languages on the Web, PHP has made its mark on the technology you know and use every day. For the examples and projects in this book, you’ll be using PHP not only for supporting asynchronous data requests to the server (AJAX), but also for shortening your development time with jQuery.

You will couple PHP with the MySQL database to support and enhance your jQuery projects.

Keep in mind that you can use any number of languages and database products with jQuery in the ways that I will present in the book—the choice is totally up to you.

PROGRESSIVE ENHANCEMENT

In 2003, Steve Champeon, speaking at the very popular SXSW Interactive conference in Austin, Texas, coined the term progressive enhancement. The concept arrived at just about the same time as some earlier JavaScript libraries.

The process behind progressive enhancement is to first develop your markup, then add style to that markup (CSS), and finally bring into play enhanced interaction via JavaScript.

In the good old days of Web development, designers and coders were stuck with a paradigm called graceful degradation. Everyone designed their sites for the latest browsers using the latest technologies and then “fixed” their pages by inserting hacks or removing JavaScript functionality so that they would gracefully degrade and be usable by older, less-capable browsers or in situations where the user might have JavaScript disabled. Developers attempted to perform browser detection using JavaScript so that they could deliver flashy interaction in every browser available. It was tiresome and frustrating. Steve Champeon’s concept changed all of that.

There is a better way to describe progressive enhancement. In his 2008 article, “Understanding Progressive Enhancement” (www.alistapart.com/articles/understandingprogressiveenhancement), on the A List Apart Web site, Aaron Gustafson painted my favorite picture of what progressive enhancement is when he wrote, “If you’re a candy fan, think of it as a Peanut M&M: Start with your content peanut, marked up in rich, semantic (X)HTML. Coat that content with a layer of rich, creamy CSS. Finally, add JavaScript as the hard candy shell to make a wonderfully tasty treat (and keep it from melting in your hands).”

Let’s examine a quick example of progressive enhancement. Here is a portion of 1-1.html (available in the code download at www.appliedjquery.com in the folder chap1/1-1.html):

<body>
    <div id="header"><h2>Progressive Enhancement Example</h2></div>
    <div id="clear"></div>
    <div id="leftContent">
        <a href="1-2.html" id="anchor" >New Content</a><br />
        <a href="http://www.google.com" rel="external">Google</a>
    </div>
    <div id="rightContent"></div>
</body>

Figure 1.7. The basic progressive enhancement page with HTML and CSS only.

Image

Figure 1.8. The result of clicking the New Content link in 1-2.html.

Image

The markup is pretty standard. Adding some basic CSS produces what you see in Figure 1.7.

I’ve also produced the HTML and CSS for a second page called 1-2.html, which is in the folder chap1/1-2.html. If you click the link for New Content, that page will load normally (Figure 1.8). The only change made, other than adding some content for this example, is in the CSS that causes the content to be displayed in a burnt orange box:

#rightContent {
    width: 75%;
    margin-left: 20px;
    padding-top: 10px;  
    padding-left: 10px;  
    background-color: #FFCC66;
    vertical-align: top;
    float: left;
}

The site works perfectly, even though it is rather bland. Let’s add just a bit of jQuery without touching any of the current markup.

1. Include the jQuery library by placing a tag in the <head> section of 1-1.html:

<head>
    <meta http-equiv="Content-Type" content="text/html;
    Image charset=ISO-8859-1" />
    <title>Progressive Enhancement Example 1-1</title>
    <script type="text/javascript" src="../inc/jQuery/8
jquery-1.5.min.js"></script>

2. Add a code block also within the <head> tags, although it is not necessary to do so, as you will see in later examples:

<script type="text/javascript">
$(document).ready(function(e) {
    $("#anchor").click(function() {
        $("#rightContent").load("1-2.html #rightContent > p");
        e.preventDefault();
    });
});
</script>

Basically, the code specifies, Anytime the element identified as anchor is clicked, load the paragraphs from 1-2.html file’s rightContent area into 1-1.html file’s content area.

Figure 1.9. The content from the second page appears without the distracting background color.

Image

Now when you click the New Content link, the page does not reload and the content appears as you expect, without the yucky background color (Figure 1.9).

Adding jQuery without using inline JavaScript tags is known as unobtrusive JavaScript and adheres to the principles of progressive enhancement. None of the HTML tags had to be changed, and if JavaScript is disabled, the pages will continue to work as designed. No more embedding JavaScript calls within the HTML tags!

In addition, the CSS here is unobtrusive, too. There are no style attributes as part of the HTML tags, but jQuery does give you the ability to change styling on the fly by giving you ways to add and remove classes and directly manipulate the CSS of every element on the page. You’ll be using these functions frequently throughout the book.

PLANNING DESIGN AND INTERACTION

Any good Web application begins on paper, perhaps with a few basic sketches. By the end of the book, you’ll have the ability to greatly enhance your sites with jQuery, so planning is especially important. You don’t want to just throw jQuery code willy-nilly into your Web pages without a plan, or soon you’ll have interaction overload. So many page elements will change and move on the screen that you’ll get your visitor’s attention, but not in the ways that you want to gain that attention.

Creating a storyboard is a great way to plan how you will guide the visitor through your site. Drawing a storyboard doesn’t require any special skill. You can use sticky notes, sketches, flowcharts, or even the UML (Unified Modeling Language) to show how potential interactions behave and pages connect to each other. Be sure to ask lots of “what ifs.” What if the viewer clicks here? What if the mouse scrolls over this section of the page? What if the total is over $100? What if you put your spinning, flaming logo right in the center of the page?

Asking questions like these and creating a basic layout of the site will open your eyes to how your visitors will see and interact with your Web pages. It will also give you some ideas for how you can build more jQuery widgets that add value to your sites.

WRAPPING UP

In this chapter, you learned about the jQuery JavaScript library, how to write the proper syntax for jQuery, and how jQuery selectors are like CSS selectors. You learned how jQuery interacts with the DOM and how you can use jQuery to traverse the DOM. You gained knowledge of tools like Firebug, jsFiddle, and the Google Closure Compiler to help you troubleshoot, test, and make your jQuery scripts ready for use on live Web sites and applications. Finally, you learned how to combine jQuery with HTML, CSS, and other languages using Progressive Enhancement techniques to keep all of your code and scripts compartmentalized for easy maintenance and to let site visitors with less-capable browsers use your content with restriction.

Now that you are armed with some good tools and an understanding of the jQuery basics, it is time to jump right in. To learn how jQuery can interact with the browser and events associated with the browser, just turn the page!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
35.171.45.182