Using the Selectors API

Excerpt from Beginning JavaScript and CSS Development with jQuery

By Richard York

Using the Selectors API in jQuery is very easy. First, you must know that everything you want to do with jQuery originates from a single, very simply named object that is called

$

. That’s right, its name is a single dollar sign. As I mentioned back in Chapter 1, you can also use “jQuery” in place of the dollar sign, but from here on throughout this book, I will use only the dollar sign, and I will refer to it either as “the dollar sign object” or “the dollar sign method,” depending on context, because it is really both a method and an object at the same time.

The dollar sign is both a method and an object because it can be used like a function call, but it also has member properties and methods that you can call. The dollar sign is named after a single dollar sign for one reason only, and that is to reduce the amount of code that you have to write. This is why a dollar sign is used instead of, say,

document.getElementsBySelector()

, which is very long, verbose, and annoying to type out.

Here’s a very simple example of how you would use this method with a selector to add a click behavior to a collection of links. Basically, the object of the following code is to force the links to open in a new window, instead of using the “target” attribute, which does not validate under XHTML Strict.

Let’s say that you have a markup document that looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
 <head>
   <meta http-equiv='content-type' content='text/html; charset=utf-8' />
   <meta http-equiv='content-language' content='en-us' />
   <title>Link</title>
   <script type='text/javascript' 
           src='../../../Source Code/jQuery/jQuery.js'>
   </script>
   <script type='text/javascript' src='Figure 2-1.js'></script>
   <link type='text/css' href='Figure 2-1.css' rel='stylesheet' />
 </head>
 <body>
   <ul id='tmpFavorites'>
       <li><a href='/content/cda'>Wrox</a></li>
       <li><a href='http://www.gizmodo.com'>Gizmodo</a></li>
       <li><a href='http://www.apple.com'>Apple</a></li>
       <li><a href='http://www.jquery.com'>jQuery</a></li>
   </ul>
  </body>
</html>

In the preceding markup document, you have a simple unordered list that contains four links. You take that markup and put it with the following CSS:

body {
   font: 16px sans-serif;
}
ul {
   list-stlye: none;
   margin: 0;
   padding: 0;
}
a {
   text-decoration: none;
}

The preceding CSS document does little more than make that list look a little prettier—it neither really adds to nor takes away from the example.

Finally, you add the following JavaScript document to the markup:

var tmpExample = {
  ready : function() {
    // Get all links... 
    $('ul#tmpFavorites li a').click(
      function($e) {
        $e.preventDefault();
        window.open(this.href, 'FavoriteLink', '');
      }
    );
  }
};
 
$(document).ready(tmpExample.ready);

The preceding code, all put together, should look something like what you see in the following figure.

When you click on a link in the example, you should see the link open in a new window or tab, depending on how you have your browser’s preferences set up to handle pop-up windows.

In the preceding example, you’re using JavaScript to force the links in the

&lt;ul&gt;

element with ID name

tmpFavorites

to open in a new window or tab. To do this, in the JavaScript, you created a JavaScript Object Literal, which isn’t the only way to create a new object—there are lots of ways to do this, but I just happen to like this one. The new object is called

tmpExample

, and it has one member method, called

ready

; then inside the

ready

method are all the things you want to do when the document is ready.

NOTE: I don’t go into much detail on the topic of object-oriented JavaScript, preferring instead to stick to the topic of jQuery. If you’d like to learn more about object-oriented JavaScript, I recommend Nicholas C. Zakas’s excellent, critically acclaimed Professional JavaScript for Web Developers, also from Wrox Press (2005; 2nd ed., 2009).

As I touched on briefly in Chapter 1, jQuery provides its own event called

ready

, which is fired as soon as the DOM has finished loading, which is different from the

onload

or

load

event, in that with the

load

event, you have to wait for all the images to load too before that event will fire. Most of the time, you don’t need to wait so long; you just want to start working with the document and adding behavior as soon as the DOM has finished loading. That’s what the last line of code does:

$(document).ready(tmpExample.ready);

The preceding line of code attaches an event that fires when the DOM has finished loading, at which time the function

tmpExample.ready

is called and executed. Note that when you reference

tmpExample.ready

, you do so without adding parentheses to the function reference—parentheses cause the function reference to be executed immediately, whereas without the parentheses you are simply referencing the function. In this case, you want the function reference to be executed when the document is ready, instead of immediately, so you assign the function to the event by referencing it without parentheses. With parentheses, you are assigning the return value of the executed function, instead of the function itself.

Now that the DOM is loaded, you want to add behaviors to the document using script. The first item is an example of jQuery’s Selectors API in action: it is a function call to the dollar sign method that uses a selector that picks a

&lt;ul&gt;

element with the ID name

tmpFavorites

that looks for descendant

&lt;li&gt;

elements within that

&lt;ul&gt;

element, then looks for descendant

&lt;a&gt;

elements within the

&lt;li&gt;

elements.

$('ul#tmpFavorites li a')

Once those

&lt;a&gt;

elements are selected, you more than likely want to do something with them. In this example, you add a

click

event to each of the

&lt;a&gt;

elements that you selected. The

click

event is added via a

click

method that is unique to jQuery:

$('ul#tmpFavorites li a').click();

What you see here is an example of how jQuery lets you chain methods together. First, you selected a bunch of

&lt;a&gt;

elements; now, you’re applying a

click

event directly to each of those

&lt;a&gt;

elements via a new method called

click()

that’s chained to the end of your selection.

Within the

click()

method, you are passing a single anonymous (i.e., nameless) function that contains the programming that you want to be executed when each

&lt;a&gt;

element is clicked on by a user.

$('ul#tmpFavorites li a').click(
  function($e) {
    $e.preventDefault();
    window.open(this.href, 'FavoriteLink', '');
  }
);

The anonymous function contains one argument called

$e

, which represents the event object. The event object is just like what you would use with the standard W3C Event API, and works even in Internet Explorer, which does not natively support the W3C Event API at the time of this writing. Internet Explorer is able to use the standard API because jQuery has patched the problem areas and created a seamless API behind the scenes. No browser upgrade required!

Next, the function call

$e.preventDefault();

prevents the default action from occurring. The default action varies depending on what element you’re referring to. In the case of the

&lt;a&gt;

element, the default action would be to navigate the window the user is using to the link specified in the

href

attribute of the

&lt;a&gt;

element.

$e.preventDefault()

prevents that default action from occurring, since you want the link to open in a new window or tab instead. If you were to omit that line,

$e.preventDefault();

, you would find that the link opens in a new window or tab in addition to the main window where the user clicked on the link, and also navigates to that page.

Finally, the code includes the line that causes the link to open in a new window or tab:

window.open(this.href, 'FavoriteLink', '');

The

window.open()

method is called with the value of the

href

attribute as its first value, followed by the name of the window or tab, followed by the arguments used for controlling the presentation of the window; an empty string causes this method to behave similarly to the

target

attribute with a value of

_blank

.

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *