Chapter 18

jQuery

In This Chapter

arrow Understanding jQuery

arrow Selecting elements

arrow Creating animations and transitions with jQuery

It’s best to have your tools with you. If you don’t, you're apt to find something you didn’t expect and get discouraged.

— Stephen King

jQuery is the most popular JavaScript framework around and is used by nearly every JavaScript programmer in order to speed up and simplify JavaScript development. In this chapter, you discover the basics of jQuery and see why it’s so popular.

ontheweb Don’t forget to visit the website to check out the online exercises relevant to this chapter!

Writing More and Doing Less

jQuery is currently used by more than 61 percent of the top 100,000 websites. It’s so widely used that many people see it as an essential tool for doing JavaScript coding.

jQuery smoothes out some of the rough spots in JavaScript, such as problems with browser compatibilities, and makes selecting and changing parts of an HTML document easier. jQuery also includes some tools that you can use to add animation and interactivity to your web pages.

The basics of jQuery are easy to learn once you know JavaScript.

Getting Started with jQuery

To get started with jQuery, you first need to include the jQuery library in your web pages. The easiest way to do this is to use a version hosted on a content delivery network (CDN). The other method for including jQuery is to download the library from the jQuery website and host it on your server. Listing 18-1 shows markup for a simple web page that includes jQuery.

tip Google has hosted versions of many different JavaScript libraries, and you can find links and include tags for them at http://developers.google.com/speed/library.

Once you’ve found a link for a CDN-hosted version, include it between your <head> and </head> tags in every page that will use jQuery functionality.

warning There are currently two branches of jQuery: the 1.x branch and the 2.xbranch. The difference between the latest versions of the 1.xbranch and the latest versions of the 2.xbranch is that the 1.xbranch works in Internet Explorer 6-8, while the 2.xbranch had eliminated support for these old and buggy browsers.

Listing 18-1: Your First Web Page with jQuery

<html>
<head>
 <title>Hello JQuery</title>
 <style>
  #helloDiv {
   background: #333;
   color: #fff;
   font-size: 24px;
   text-align: center;
   border-radius: 3px;
   width: 200px;
   height: 200px;
   display: none;
  }
 </style>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
 <button id="clickme">Click me!</button>
 <div id="helloDiv">Hello, JQuery!</div>

 <script>
 $( "#clickme" ).click(function () {
  if ( $( "#helloDiv" ).is( ":hidden" ) ) {
   $( "#helloDiv" ).slideDown( "slow" );
  } else {
   $( "div" ).hide();
  }
 });
 </script>
</body>
</html>

The jQuery Object

All of jQuery’s functionality is enabled by the jQuery object. The jQuery object can be referenced using two different methods: the jQuery keyword or the $ alias. Both methods work exactly the same. The difference is that $ is shorter, and so it’s become programmers' preferred method for using jQuery.

The basic syntax for using jQuery is the following:

$("selector").method();

The first part (in parentheses) indicates what elements you want to affect, and the second part indicates what should be done to those elements.

In reality, jQuery statements often perform multiple actions on selected elements by using a technique called chaining, which just attaches more methods to the selector with additional periods. For example, in Listing 18-2, chaining is used to first select a single element (with the ID of pageHeader) and then to style it.

Listing 18-2: Using Chaining

<html>
<head>
 <title>JQuery Chaining Example</title>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
 <div id="pageHeader"/>
 <script type="text/javascript">
  $("#pageHeader").text("Hello, world!").css("color", "red").css("font-size", "60px"); 
 </script>
</body>
</html>

Chained jQuery methods can get pretty long and confusing after you put just a couple of them together. However, keep in mind, JavaScript doesn’t really care much about whitespace. It’s possible to reformat the chained statement from Listing 18-2 into the following, much more readable, statement:

$("#pageHeader")
  .text("Hello, world!")
  .css("color", "red")
  .css("font-size", "60px");

Is Your Document Ready?

jQuery has its own way to indicate that everything is loaded and ready to go: the document ready event. To avoid errors caused by the DOM or jQuery not being loaded when the scripts run, it’s important to use document ready, unless you put all your jQuery at the very bottom of your HTML document (as we do with Listing 18-1 and Listing 18-2.)

Here’s the syntax for using document ready:

$(document).ready(function(){

  // jQuery methods go here…

});

Any jQuery that you want to be executed upon loading of the page needs to be inside of a document ready statement. Named functions can go outside of document ready, of course, because they don’t run until they’re called.

Using jQuery Selectors

Unlike the complicated, and limited, means that JavaScript provides for selecting elements, jQuery makes element selection simple. In jQuery, programmers can use the same techniques they use for selecting elements with CSS. Table 18-1 lists the most frequently used jQuery and CSS selectors.

Table 18-1 The Common jQuery/CSS Selectors

Selector

HTML Example

jQuery Example

element

<p></p>

$('p').css('font-size','12')

.class

<p class="redtext"></p>

$('.redtext').css

#id

<p id="intro"></p>

$('#intro').fadeIn('slow)

[attribute]

<p data-role="content"></p>

$('[data-role]').show()

In addition to these basic selectors, you canmodify a section or combine selections in many different ways. For example, to select the first p element in a document, you can use

$(‘p:first’)

To select the last p element, you can use

$(‘p:last’)

To select the even numbered elements, you can use

$(‘li:even’)

To select the odd numbered elements, you can use

$(‘li:odd’)

To combine multiple selections, you can use commas. For example, the following selector selects all the p, h1, h2, and h3 elements in a document.

$(‘p,h1,h2,h3’)

You can selecteelements in many more ways with jQuery than with plain JavaScript. To see a complete list, visit www.dummies.com/extras/codingwithjavascript.

Changing Things with jQuery

After you make a selection, the next step is to start changing some things. The three main categories of things you can change with jQuery are attributes, CSS, and elements.

Getting and setting attributes

The attr() method gives you access to attribute values. All that you need in order to use attr() is the name of the attribute whose value you want to get or set. In the following code, the attr() method is used to change the value of the href attribute of an element with an id of "homepage-link".

$(‘a#homepage-link’).attr(‘href’) = "http://www.codingjsfordummies.com/";

The result of running this statement is that the selected element’s href attribute will be changed in the DOM to the new value. When a user clicks the modified link, the browser will open the web page at the specified address, rather than the one that was originally written in the img element.

remember Modifying an element using jQuery changes only the element’s representation in the DOM (and therefore on the user’ screen). jQuery doesn’t modify the actual web page on the server, and if you view the source of the web page, you won’t see any changes.

Changing CSS

Changing CSS using jQuery is very similar to the technique we describe in Chapter 13 for modifying the Style object’s properties. jQuery makes modifying the style properties much easier than standard JavaScript, and the style properties are spelled exactly the same as in CSS.

Listing 18-3 combines live CSS style changes with form events to give the user control over how large the text is.

Listing 18-3: Manipulating Styles with jQuery

<html>
<head>
 <title>JQuery CSS</title>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
  
  $('#sizer').change(function() {
   $('#theText').css('font-size',$('#sizer').val());
  });
  });
 </script>
</head>
<body>
 <div id="theText">Hello!</div>
 <form id="controller">
  <input type="range" id="sizer" min="10" max="100">
 </form>
</body>
</html>

Figure 18-1 shows the results of running Listing 18-3 in a browser.

image

Figure 18-1: Changing CSS with an input element.

Manipulating elements in the DOM

jQuery features several methods for changing the content of element, moving elements, adding element, removing elements, and much more. Table 18-2 lists all the available methods for manipulating elements within the DOM.

Table 18-2 Manipulating Elements within the DOM

Method

Description

Example

text()

Gets the combined text content of the matched elements, or sets the text content of the matched elements

$('p').text('hello!')

html()

Get the value of the first matched element, or set the contents of every matched element

$('div').html('<p>hi</p>')

val()

Get the value of the first matched element, or set the value of every matched element

$('select#choices').val()

append()

Insert content to the end of the matched elements

$('div #closing').append('<p>Thank You</p>')

prepend()

Insert content at the beginning of the matched elements

$('dive #introduction').prepend('<p>To whom it may concern:</p>')

before()

Insert content before the matched elements

$('#letter').before(header)

after()

Insert content after the matched elements

$('#letter').after(footer)

remove()

Remove the matched elements

$('.phonenumber').remove()

empty()

Remove all of the child nodes of the matched elements

$('.blackout').empty()

Events

Chapter 11 discusses the different methods for registering event handlers in JavaScript, which are all still perfectly valid in jQuery. However, jQuery has its own syntax for registering event listeners and handling events.

jQuery’s event method, on(), handles all of the complexity of ensuring that all browsers will handle events in the same way, and it also requires far less typing than the pure JavaScript solutions.

Using on() to attach events

The jQuery on() method works in much the same way as addEventListener(). It takes an event and a function definition as arguments. When the event happens on the selected element (or elements), the function is executed. Listing 18-4 uses on() and a jQuery selector to change the color of every other row in a table when a button is clicked.

Listing 18-4: Changing Table Colors with the Click of a Button

<html>
<head>
 <title>jQuery CSS</title>
 <style>
  td {
   border: 1px solid black;
  }
 </style>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
  
   $('#colorizer').on('click',function() {
    $('#things tr:even').css('background','yellow');
   });
 });

 </script>
</head>
<body>
 <table id="things">
  <tr>
   <td>item1</td>
   <td>item2</td>
   <td>item3</td>
  </tr>
  <tr>
   <td>apples</td>
   <td>oranges</td>
   <td>lemmons</td>
  </tr>
  <tr>
   <td>merlot</td>
   <td>malbec</td>
   <td>cabernet sauvignon</td>
  </tr>
 </table>
 <form id="tableControl">
  <button type="button" id="colorizer">Colorize</button>
 </form>
</body>
</html>

Figure 18-2 shows the alternating table colors after the button is clicked.

image

Figure 18-2: Alternating table colors.

tip Do you notice something seemingly odd about the colorized rows in Figure 18-2? The first and third rows of the table are colorized, but we told jQuery to colorize the even numbered rows. The explanation is simple: The even and odd determinations are based on the index number of the tr elements, which always start with 0. So, the colorized ones are the first (index number 0) and the third (index number 2).

Detaching with off()

The off() method can be used to unregister a previously set event listener. For example, if you want to disable the button in Listing 18-4 (maybe until the user paid for the use of this feature), you use the following statement:

$(‘#colorizer’).off(‘click’);

Or, if you want to remove all event listeners on an element, you can do so by calling off with no arguments:

$(‘colorizer’).off();

Binding to events that don’t exist yet

With the dynamic nature of today’s web, you sometimes need to register an event listener to an element that is created dynamically after the HTML loads.

To add event listeners to elements that are created dynamically, you can pass a selector that should be monitored for new elements to the on() method. For example, if you want to make sure that all rows, and all future rows, in the table are clickable, you can use the following statement:

$(document).on(‘click’,‘tr’,function(){
  alert("Thanks for clicking!");
}

Other event methods

Besides on(), jQuery also has a simplified shortcut syntax for attaching event listeners to selected elements. jQuery has methods with the same names as the events that you can just pass the event handler to. For example, both of these statements accomplish the same thing:

$(‘#myButton’).on(‘click’,function() {
  alert('Thanks!');
}
$(‘#myButton’).click(function() {
  alert('Thanks!');
}

Other shortcut event methods include

  • change()
  • click()
  • dblclick()
  • focus()
  • hover()
  • keypress()
  • load()

For a complete list of event methods, visit the jQuery website at http://api.jquery.com/category/events.

Effects

jQuery makes a JavaScript programmer’s life much easier. It even makes simple animations and effects easier.

warning jQuery effects are so simple that they’re often overused. Once you see what can be done and have played with each of the different variations, it would probably be a good idea to build one web app that uses them all every time any event happens. Then, delete this file and consider this urge to overuse effects to be out of your system.

Basic effects

jQuery’s basic effects simply control whether selected elements are displayed or not. The basic effects are

  • hide(): The hide method hides the matched elements.
  • show(): The show method shows the matched elements
  • toggle(): The toggle method toggles between hiding and showing the matched elements. If the matched element is hidden, toggle will cause it to be shown. If it’s shown, toggle will cause it to be hidden.

Fading effects

You can transition selected elements between displaying and hiding by using a fade effect. The fading effects are

  • fadeIn(): The fadeIn method causes the matched element to fade into view over a specified amount of time (become opaque).
  • fadeOut(): The fadeout method causes the matched element to fade out over a specified amount of time (become transparent).
  • fadeTo(): The fadeTo method can be used to adjust the opacity of elements to a specified level over a specified amount of time.
  • fadeToggle(): The fadeToggle method fades matched elements in or out over a specified amount of time.

Sliding effects

The sliding effects transition selected elements between showing and hiding by using an animated slide effect. The sliding effects are

  • slideDown(): The sildeDown method displays the matched elements with an upward sliding motion.
  • slideUp(): The slideUp method hides the matched elements with an upward sliding motion.
  • slideToggle(): The slideToggle method toggles between sliding up and sliding down.

Setting arguments for animation methods

Each of the jQuery animation methods has a set of optional arguments that control the details of how the animation takes places and when.

The arguments of the basic, sliding and fading methods are

  • duration: Duration is a numeric value indicating how long (in milliseconds) the animation should take.
  • easing: Easing is a string value telling what easing function should be used to do the animation. An easing function determines how the element animates. For example, it may start slow and speed up or start fast and slow down. jQuery has two easing functions built-in:
    • swing (default): Progress slightly lower at the beginning and end than in the middle.
    • linear: Progress at a constant rate through the animation.
  • complete: The complete argument specifies a function to execute when the current animation is finished.

Custom effects with animate()

The animate method performs a custom animation of CSS properties. To specify the animation, you pass a set of properties to the animate method. When it runs, the animation will move toward the values you set for each property. For example, to animate increasing with width and color of a div, you could use this statement:

(‘div #myDiv’).animate(
{
  width: 800,
  color: 'blue'
}, 5000);

In addition to the required CSS properties argument, the animate method takes the same optional arguments as the other animation methods.

Playing with jQuery animations

Listing 18-5 implements several of the jQuery animation methods. Try changing values and experimenting with the different settings for each of these methods and see what you come up with!

Listing 18-5: Fun with jQuery Animations

<html>
<head>
 <title>JQuery CSS</title>
 <style>
   td {
    border: 1px solid black;
  }
 </style>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
 <script type="text/javascript">
  // wait for the DOM to be ready
  $(document).ready(function(){
   // when the animator button is clicked, start doing things
  $('#animator').on('click',function() {
    $('#items').fadeToggle(200);
    $('#fruits').slideUp(500);
    $('#wines').toggle(400,'swing',function(){ $('#wines').toggle(400,'swing');
    });
    $('h1').hide();
    $('h1').slideDown(1000).animate({ 'color': 'red', 'font-size': '100px'},1000),;
   });
  });
 </script>
</head>
<body>
 <h1>Here are a bunch of things!</h1>
 <table id="things">
   <tr id="items">
   <td>item1</td>
   <td>item2</td>
   <td>item3</td>
  </tr>
  <tr id="fruits">
   <td>apples</td>
   <td>oranges</td>
   <td>lemmons</td>
  </tr>
  <tr id="wines">
   <td>merlot</td>
   <td>malbec</td>
   <td>cabernet sauvignon</td>
  </tr>
 </table>
 <form id="tableControl">
  <button type="button" id="animator">Animate Stuff!</button>
 </form>
</body>
</html>

AJAX

One of the most useful things about jQuery is how it simplifies AJAX and makes working with external data easier.

Chapter 16, discusses AJAX, the technique of loading new data into a web page without refreshing the page. It also covers how to use JSON data in JavaScript.

Using the ajax() method

At the head of jQuery's AJAX capabilities lies the ajax() method. The ajax() method is the low-level way to send and retrieve data from an external file. At its most simple, the AJAX method can take just a filename or URL as an argument, and it will load the indicated file. Your script can then assign the content of that file to a variable.

You can also specify many different options about how the external URL should be called and loaded, and you can set functions that should run if the request succeeds or fails.

For a complete list of the optional arguments of the ajax() method, visit http://api.jquery.com/jQuery.ajax.

In Listing 18-6, the script opens a text file containing a paragraph of text and displays that text inside of a div element.

Listing 18-6: Loading and Displaying an External File with jQuery and AJAX

<html>
<head>
 <title>Dynamic Introduction</title>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
 <script>
  // wait until everything is loaded
  $(document).ready(function(){
   // when the button is clicked
   $('#loadIt').on('click',function(){
    // get the value of the select and add .txt to it
    var fileToLoad = $('#intros').val() + '.txt';
    // open that file
    $.ajax({url:fileToLoad,success:function(result){
 // if successful with opening, display the file contents
 $('#introtext').html(result);
    }});
   });
  });
 </script>
</head>
<body>
 <h1>Select the type of introduction you would like:</h1>
 <form id="intro-select">
  <select id="intros">
   <option value="none">Please Select</option>
   <option value="formal">Formal</option>
   <option value="friendly">Friendly</option>
   <option value="piglatin">Piglatin</option>
  </select>
  <button id="loadIt" type="button">Load It!</button>
 </form>
 <div id="introtext"></div>
</body>
</html>

warning If you try to run Listing 18-6 on your local computer, you’ll run into the browser security restriction called same-origin policy, which won’t allow data to load via AJAX unless it’s loading from the same domain (see Chapter 16). To try out this example, visit http://www.codingjsfordummies.com/extras/coding with javascript , upload it to your own web server, or disable your browsers security restrictions.

Shorthand AJAX methods

jQuery also has several shorthand methods for handling AJAX. The syntax for these is simplified because they’re designed for specific tasks. The shorthand AJAX methods are as follows:

  • .get() loads data from a server using an HTTP GET request.
  • .getJSON() loads JSON data from a server using an HTTP GET request.
  • .getScript() loads a JavaScript file from a server using an HTTP GET request and then executes it.
  • .post() loads data from a server and place the returned HTML into the matched element.

To use the shorthand methods, you can pass them a URL and, optionally, a success handler. For example, to get a file from a server using the get() method and then insert it into the page, you can do the following:

$.get( "getdata.html", function( data ) {
  $( ".result" ).html( data );
});

The preceding example is equivalent to the following full .ajax() statement:

$.ajax({
  url: getdata.html,
  success: function( data ) {
  $( ".result" ).html( data );
  }
});

The savings in effort isn’t enormous in this example. With more complex AJAX requests, learning and using the shorthand AJAX can result in more understandable and concise code.

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

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