Home Web Development jQuery 2.0 Development Cookbook

jQuery 2.0 Development Cookbook

By Leon Revill
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Document Object Model Manipulation
About this book
Publication date:
February 2014
Publisher
Packt
Pages
410
ISBN
9781783280896

 

Chapter 1. Document Object Model Manipulation

In this chapter, we will cover:

  • Selecting elements

  • Finding and selecting sibling elements

  • Creating DOM elements

  • Inserting content into an element

  • Modifying the DOM element properties

  • Adding and removing CSS classes to dynamically change their style

  • Enabling and disabling buttons by changing their properties

  • Updating an image within a page

  • Populating list elements

  • Understanding pagination

  • Removing DOM elements

  • Re-using DOM elements

 

Introduction


This chapter looks at the fundamental principles of jQuery—finding, selecting, and manipulating DOM elements. jQuery makes it easy for JavaScript developers to select single or multiple HTML page elements using a variety of methods.

Once the developer has selected these elements, jQuery provides the ability to manipulate each of these elements in order to create a richer user experience through attribute modifications such as style, disabled, and class.

 

Selecting elements


There are many ways in which you can use jQuery to select DOM elements. We will explore the main methods here. For developers familiar with CSS, it is possible to use the same syntax when selecting elements with jQuery (that is, #content, .content, and so on).

Getting ready

Open a blank HTML document within your text editor or IDE of choice. Ensure that you have the latest version of jQuery downloaded and is easily accessible for inclusion into this HTML document. When creating new HTML files within this chapter, ensure that they are all within the same directory as the jQuery library file, making it easy to include into the HTML document.

How to do it…

To understand how you can use jQuery to select a variety of DOM elements, perform each of the following recipe steps:

  1. Create a web page using the following HTML and JavaScript code:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Selecting Elements with jQuery</title>
       <script src="jquery.min.js"></script>
       <script>
          $(function(){
             var content = $("#content"); //Select the content div
             var span = $(".span-element"); //Select the span element
             var listelements = $("li"); //Select all the list elements
          });
       </script>
    </head>
    <body>
    <div class="division-container">Some text within a div which has a class</div>
    <div id="content">Some text within a div which has an ID attribute</div>
    <a href="#">A link</a>
    <a href="#" rel="dofollow">A second link</a>
    <ul class="info-list">
       <li>List Item 1</li>
       <li>List Item 2</li>
       <li>List Item 3</li>
    </ul>
    <button>Button 1</button>
    <span class="span-element">Span 1</span>
    </body>
    </html>
  2. To select any of these elements, use the jQuery's $() function. We can use this function in conjunction with an identifier or CSS selector for an element we would like to select; for example, its HTML tag li and ID #content or a class .content.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How it works…

The simplest method of selecting a DOM element is by its ID. We know that all IDs within a HTML document should be unique; therefore, by selecting an element with its ID, you will be selecting a single element.

In reference to the preceding HTML document, if you wanted to select <div>, which has an ID content, you can use the following jQuery code to select it:

$(function(){
   var content = $('#content');
});

This would make the DOM element available within the content variable. More on what this means is covered later in the chapter.

Note

Any code within $(function(){ }); will be automatically executed by jQuery when the page is loaded.

We can also select elements in the same way using their class. The code is very similar to the preceding example, except that we use the class prefix (.) instead of the ID prefix (#), illustrated as follows:

$(function(){
   var span = $('.span-element');
});

Not only can we select elements based on some identifier we specify (that is, class or ID), but we can also select elements based on their tag name. If you wanted to select all the li elements within a page, you would use $('li'), illustrated as follows:

$(function(){
   var listelements = $('li');
   var i = 1;
   listelements.each(function(){
      console.log("Loop: " + i);
      i++;
   });
});

The preceding example uses the jQuery selector to select all the list elements within the page. To demonstrate that listelements now contains multiple elements, we loop through these and output some information to the console.

Note

.each() is a jQuery function. Learn more about its uses in Chapter 3, Loading and Manipulating Dynamic Content with AJAX and JSON.

The console output for the preceding example is as follows:

Loop: 1
Loop: 2
Loop: 3

Note

You can access the JavaScript console in various ways depending on your choice of browser:

  • Chrome: Ctrl + Shift + J (Mac: command + option + J)

  • Internet Explorer: F12

  • Firefox: Ctrl + Shift + K

There's more…

It is also possible to select elements based on other properties such as their rel or disabled attributes.

The following code shows us how we can select an anchor element that has a rel attribute of nofollow:

$(function(){
   var nofollow = $('a[rel="nofollow"]');
});

See also

  • Finding and selecting sibling elements

 

Finding and selecting sibling elements


You may not always know the specific element that you need to select. You may only know its parent, and therefore, you will need to search through the elements within the parent in order to find the specific element that you are looking for. This recipe will show you how to find elements through their parents in various ways.

Getting ready

Open your text editor or IDE with the latest version of jQuery, ready to be included into the HTML page that you will create as part of this recipe.

How to do it…

To learn the various ways in which jQuery can help you to search for DOM elements based on a parent element, perform each of the following steps:

  1. Create a web page with the following HTML and JavaScript code:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Finding and selecting sibling elements</title>
       <script src="jquery.min.js"></script>
       <script>
          $(function(){
             var element1 = $('#content .top .top-left'); //Select the top left division element
             var element2 = $('.parent').find('a'); //Select the anchor element
             var element3 = $('.parent').find('.grandchild'); //Select the grandchild element
          });
       </script>
    </head>
    <body>
    <div class="division-container">Some text <span>within</span> a div <span>which</span> has a many <span>span</span> elements.</div>
    <div id="content">
       <div class="top">
          <div class="top-left">Left</div>
          <div class="top-right">Right</div>
       </div>
    </div>
    <ul class="info-list">
       <li>List Item 1</li>
       <li>List Item 2</li>
       <li>List Item 3</li>
    </ul>
    <ul class="second-info-list">
       <li>Second List Item 1</li>
       <li>Second List Item 2</li>
       <li>Second List Item 3</li>
    </ul>
    <div class="parent">
       <div class="child">
          <div class="grandchild">
             <a href="#">A Link</a>
          </div>
       </div>
    </div>
    </body>
    </html>
  2. This code uses multiple class names in the same way as you would use them with CSS to select child elements from HTML. Alternatively, you can use jQuery's find() function on a parent element to search within.

How it works…

The simplest way to select a child element based on its parent is by using the same selectors as you would in CSS (that is, .classname .anotherclass). Having said this, you do not always know the exact location of the sibling element you are looking for. If this is the case, we can use the useful jQuery's find() function. jQuery's find() function will search within the specified parent element for the sibling element that you are looking for.

Based on the HTML within the How to do it… section, the following JavaScript illustrates how you can access a child element directly in the same manner as you would in CSS:

$(function(){
   var element1 = $('#content .top .top-left');
});

This would make the DOM element available within the content variable. More on what this means is covered later in the chapter.

To find a child element without knowing its exact location, we can use the following JavaScript to locate the anchor within the <div class="grandchild"> element:

$(function(){
   var element2 = $('.parent').find('a');
});

Note that you only need to specify the parent selector and the element you are looking for. The find() method simply traverses the DOM based on the specified parent element until it either finds the element you are looking for or runs out of elements to check against. You can use ID and class names within the find() method as well as HTML notations.

There's more…

You can also use CSS3 selectors such as :first-child and :last-child within $() to help you select the required DOM element.

See also

  • Selecting elements

 

Creating DOM elements


To create rich and interactive user interfaces, we need to be able to dynamically add DOM elements to a web page. Elements may need to be added to a web page based on user interaction or another event such as page load.

Getting ready

For this recipe, you are going to need another blank HTML file. Create a new HTML file named recipe-3.html within the same directory as the one used for the previous recipe's files.

How to do it…

Learn how to create DOM elements with jQuery by performing the following steps:

  1. Add the following HTML code to your recipe-3.html file in order to create a basic HTML page with an unordered list and include the jQuery library:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Creating DOM elements</title>
       <script src="jquery.min.js"></script>
       <script></script>
    </head>
    <body>
    <div id="container">
       <ul id="myList">
          <li>List Item 1</li>
          <li>List Item 2</li>
          <li>List Item 3</li>
       </ul>
    </div>
    </body>
    </html>
  2. Add the following JavaScript within the script tags in the head of the HTML document. The following JavaScript code will add two buttons to the DOM after the #myList element utilizes jQuery's after() and insertAfter() functions:

    $(function(){
       $('#myList').after("<button>Button 1</button>");
       $('<button>Button 2</button>').insertAfter("#myList");
    });

How it works…

To dynamically add DOM elements to any part of the document, we can use the append(), addAfter(), after(), addBefore(), and before()functions of jQuery. The functions after() and insertAfter() essentially perform the same action; the difference lies in the order in which the expressions are specified. This is the same for insertBefore() and before().

Based on the HTML file in the How to do it... section, the following JavaScript will add two button elements after the unordered list element:

$(function(){
   $('#myList').after("<button>Button 1</button>");
   $('<button>Button 2</button>').insertAfter("#myList");
});

Once the preceding JavaScript has been executed, the HTML rendered in the browser should be modified as follows:

<!DOCTYPE html>
<html>
<head>
   <title> Creating DOM elements</title>
   </head>
<body>
<div id="container">
   <ul id="myList">
      <li>List Item 1</li>
      <li>List Item 2</li>
      <li>List Item 3</li>
   </ul>
      <button>Button 2</button>
      <button>Button 1</button>
</div>
</body>
</html>

Note that even though the second button was added last, it is first in the HTML. This is because we have specified that the button should be inserted after the unordered list element. Both .before() and .insertBefore() jQuery methods work exactly in the same way, except that the button elements would be above the unordered list element.

A common requirement of dynamic web pages and web applications is to be able to add new items to a list. This is best achieved using the .append() function:

$(function(){
   $('#myList').append("<li>List Item 4</li>");
});

This JavaScript will add the new list item with the text List Item 4 to the bottom of the #myList unordered list element. Alternatively, the prepend() function could be used to insert the list item at the top of the list.

There's more…

jQuery provides developers with many ways to add, append, insert, and update elements into the DOM that could not be demonstrated within a single recipe. Ensure that you are aware of the alternatives by reading the jQuery documentation.

See also

  • Inserting content into an element

  • Removing DOM elements

  • Re-using DOM elements

 

Inserting content into an element


Interactive and dynamic web applications and websites not only require the web developer to be able to create DOM elements but also require the developer to be able to add dynamic content. This is easily achievable with another set of jQuery functions.

Getting ready

Create a blank HTML document named recipe-4.html, and ensure that you have the latest version of jQuery available to be included within this HTML document.

How to do it…

Learn how to dynamically add content into the DOM by performing each of the following steps:

  1. Add the following code to your newly created HTML document, which will create a simple HTML web page:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Insert content into an element</title>
       <script src="jquery.min.js"></script>
       <script>
          
       </script>
    </head>
    <body>
    <div id="container">
       <p>Here is some current HTML content</p>
    </div>
    <textarea id="myTextarea"></textarea>
    </body>
    </html>
  2. Insert the following JavaScript code within the script tags in the document head. This code will inject different HTML content and elements into the DOM at various points.

    $(function(){
       //Remove the container elements current HTML
       $('#container').html("<p>I have replaced the all the HTML within the #container element</p>");
    
       //Add some more HTML to the beginning of the container element
       $('#container').prepend("<p>Another paragraph that has been prepended.</p>");
    
       //Add a button to the end of the container element after all other HTML content
       $('#container').append("<button>A Button Appended</button>");
    
       //Add some text into the text area element
       $('#myTextarea').val("Added some text using .text()");
    });

How it works…

The quickest way to add content to an element is to use the html() function. By providing this function with a string as an argument, it will replace the selected element's current DOM contents with the provided string. If no string is provided, this function will return the element's DOM contents formatted as an HTML string.

Besides replacing the content of an element, we can also use append() and prepend() to add additional content at the end and at the beginning of the current content, respectively. Additionally, we have other functions available such as text(), which will decode any HTML before it inserts the string within the element. The text() function is typically used for text areas for this reason.

Based on the HTML provided in the previous section, we can alter the content of the #container element using the jQuery functions previously discussed as follows:

$(function(){
$('#container').html("<p>I have replaced the all the HTML within the #container element</p>");

$('#container').prepend("<p>Another paragraph that has been prepended.</p>");

$('#container').append("<button>A Button Appended</button>");

$('#myTextarea').val("Added some text using .text()");
});

After each of these functions has been executed, the HTML file rendered by the browser will be transformed, which is illustrated as follows:

<!DOCTYPE html>
<html>
<head>
   <title>Insert content into an element</title>
</head>
<body>
<div id="container">
   <p>Another paragraph that has been prepended.</p><p>I have replaced the all the HTML within the #container element</p>
   <button>A Button Appended</button>
</div>
<textarea id="myTextarea">Added some text using .text()</textarea>
</body>
</html>

See also

  • Creating DOM elements

 

Modifying the DOM element properties


We can use jQuery to dynamically modify element properties such as class, style, and disabled, which means that it is possible to visually alter and change the function of a range of HTML elements.

Getting ready

Once again, this recipe requires an additional blank HTML document. Create a file named recipe-5.html, and have it open and ready for editing.

How to do it…

Learn how to alter the properties of the DOM element by performing each of the following steps:

  1. Add the following HTML code to your blank recipe-5.html file in order to create a basic HTML page with two types of inputs:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Modifying DOM element attributes and properties</title>
       <script src="jquery.min.js"></script>
       <script>
    
       </script>
    </head>
    <body>
    <input type="checkbox" />
    <input type="text" />
    </body>
    </html>
  2. Within the preceding HTML code, add the following JavaScript code inside the script tags to disable the input, modify its value, and check the checkbox:

    $(function(){
       //Set the checkbox to be checked
       $('input[type="checkbox"]').prop('checked', true);
       //Disable any text inputs
       $('input[type="text"]').prop('disabled', true);
       //Change the value of any text inputs
       $('input[type="text"]').val("This is a new Value!");
    });

How it works…

jQuery provides us with a prop() function that will either retrieve the specified property if no value is specified, or if a value is provided, it will alter the specified property on the selected element. This can be used to change property values such as checked on a checkbox or the disabled property on a text input. We could use the prop() function to alter the value of a text input; however, it is preferable to use the val() function that is available specifically for this task.

Typically, this would be done based on a user-triggered event, but to illustrate this as simply as possible, the following JavaScript does so on page load:

$(function(){
   $('input[type="checkbox"]').prop('checked', true);
});

This JavaScript will check each input within the page that is of the type checkbox. Similarly, we can alter the disabled state of a text input with only a few modifications:

$(function(){
   $('input[type="text"]').prop('disabled', true);
});

We can also use the val() function to add some text to each of these text inputs using the following JavaScript:

$(function(){
    $('input[type="text"]').val("This is a new Value!");
});

Often, you can chain functions with jQuery. You can achieve the previous two actions by using both the functions inline (that is, $('input[type="text"]').prop('disabled', true).val("This is a new Value!");), and they will be executed in turn.

See also

  • Enabling and disabling buttons by changing their properties

  • Adding and removing CSS classes to dynamically change their style

 

Adding and removing CSS classes to dynamically change their style


jQuery comes bundled with class manipulation functions in order to allow developers to easily alter the style of any HTML element.

Getting ready

For element style changes to be of any use, we first need to declare some styles within an HTML document. The following HTML code has a range of styles and elements that we can work with to illustrate this functionality of jQuery:

<!DOCTYPE html>
<html>
<head>
   <title>Add and remove CSS classes to dynamically change their style</title>
   <script src="jquery.min.js"></script>
   <script></script>
   <style type="text/css">
      .green {
         background-color: #008000;
         color: #FFFFFF;
      }
      .red {
         background-color: #FF0000;
         color: #FFFFFF;
      }
      .yellow {
         background-color: #FFFF00;
         color: #000000;
      }
   </style>
</head>
<body>
   <p id="sometext">
      Here is some text that can have different styles applied to it dynamically</p>
   <button id="green-btn">Green</button>
   <button id="red-btn">Red</button>
   <button id="yellow-btn">Yellow</button>
</body>
</html>

Within this HTML code, we have three buttons with their own unique IDs. We also have a paragraph with an ID. There are three CSS classes defined: green, red, and yellow. With jQuery, we can listen for the click of either of these buttons and then dynamically apply one of these classes to the paragraph element.

If you save this HTML file and open it within a browser, you should have the following web page:

How to do it…

  1. Add the following JavaScript code within the script tags in the HTML page you have just created:

    $(function(){
       //Listen for a click event on the green button
    $('#green-btn').click(function(){
       //When the green button has been clicked
       //Remove all classes current on the #sometext paragraph
       $('#sometext').removeClass();
       //Add the .green class to the #sometext paragraph
       $('#sometext').addClass('green');
    });
       //Listen for a click on the red button
    $('#red-btn').click(function(){
       //When the red button has been clicked
       //Remove all classes from the #sometext paragraph
       $('#sometext').removeClass(); 
       //Add the .red class to the #sometext paragraph 
       $('#sometext').addClass('red');
       });
       //Listen for a click on the yellow button
       $('#yellow-btn').click(function(){
          //When the yellow button has been clicked
          //Remove all classes from the #sometext paragraph
       $('#sometext').removeClass();
       //Add the .yellow class to the #sometext paragraph 
       $('#sometext').addClass('yellow');
       });
    });
  2. Opening the HTML document in your browser will now allow you to change the #sometext paragraph style by selecting either of the three available buttons.

How it works…

jQuery allows us to attach a click event handler to any element by using the click() function. We can then execute a set of code of our choice by passing a function as an argument to the click() method. To add a class to an element, we can use the addClass() function and provide the class name as a string argument. This function will add the specified class name to the selected element.

jQuery also provides us with a removeClass() function. This allows us to either remove a specific class from an element by providing removeClass() with a string, or when a string is not provided, it will remove all the classes from the selected element. We will need to use this in order to prevent multiple classes being added to the paragraph element when either of the buttons has been clicked more than once.

The following screenshot illustrates this web page after the Yellow button has been clicked:

See also

  • Modifying the DOM element properties

  • Enabling and disabling buttons by changing their properties

 

Enabling and disabling buttons by changing their properties


The ability to dynamically enable and disable buttons is particularly useful for situations such as saving data to a web server. In order to prevent a user from making multiple save requests while the request is being made and the client is waiting for a response, you can dynamically disable the save button. Once the client has received a response from the web server, you can re-enable the save button.

This functionality can also be very effective in simple situations, such as enabling the search button when the user has inputted a search term. This makes it clear to the user that they cannot search unless a term has been entered.

Getting ready

Create a blank HTML document named recipe-7.html, and have it open and ready for editing.

How to do it…

  1. The following HTML code creates a web page with a search input and a search button, which is disabled by default. Add the following code to recipe-7.html:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Enable and disable buttons by changing their properties </title>
       <script src="jquery.min.js"></script>
       <script>
    
       </script>
    </head>
    <body>
       <input type="text" id="search-input" />
       <button id="search-btn" disabled>Search</button>
    </body>
    </html>
  2. Saving and opening this HTML in a browser should provide you with a very simple web page having a single input and a disabled button as illustrated in the following screenshot:

  3. Add the following JavaScript within the script tags in the head section of the HTML document created previously:

    $(function(){
       //Listen for a key up event on the search input
    $('#search-input').keyup(function(){
         //When a user presses and releases a key
         //Check to see if the length of the inputted 
         //data is greater than 2 
         if ($(this).val().length > 2) {
            //If the input length is greater than 
            //two then we enable the search button
            $('#search-btn').prop("disabled", false);
       } else {
          //If the input length is equal to 2 or less we disable the search button
          $('#search-btn').prop("disabled", true);
       }
    });
    });
  4. Opening this page within a web browser will provide you with an input and a disabled search button until you enter some text into the search input. When text is entered into the search input and the length of the text is greater than two characters, the search button will become available.

How it works…

Our aim is to enable the search button once there has been some text inputted into the search input by the user. To do this, we need to attach a .keyup() event handler to the search input. This will allow us to execute some code while the user is inputting some text. By providing a function as an argument to the keyup() function, we can then check the inputted data. If the input data has a length of two or more characters (as a search less than three characters would be a little ambiguous), we can enable the search button.

Using the following JavaScript, we are able to listen for data input, check the input length, and depending on this, enable or disable the search button:

$(function(){
$('#search-input').keyup(function(){
   if ($(this).val().length > 2) {
      $('#search-btn').prop("disabled", false);
   } else {
   $('#search-btn').prop("disabled", true);
   }
});
});

First of all, we attach the keyup event to the search input using $('#search-input').keyup();, referencing its ID. Then, within the callback function, we are able to check the length of the currently inputted text using $(this), which refers to the element to which we have attached the keyup event. The val() function then gets the inputted text, and we can use the length property to find its length. Using an if/else statement, we can decide if the search button needs to be enabled or disabled.

To enable or disable the search button, we use jQuery's prop() function and set the disabled property to either true or false.

See also

  • Modifying the DOM element properties

  • Adding and removing CSS classes to dynamically change their style

 

Updating an image within a page


jQuery allows the developer to dynamically change images on a web page. This recipe will show you how to do this and also show you how to use a timestamp in order to prevent the browser from using a cached image, which can often be a problem when swapping images dynamically in this way.

Getting ready

For this recipe, you are going to need four different images. Ensure that you have four small images named black.png, red.png, blue.png, and green.png available.

How to do it…

To understand how jQuery can be used to change an image, complete each of the following steps:

  1. Create a file named recipe-8.html within an easily accessible directory, and add the following HTML code to this file:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Change an image source and tackle browser caching to ensure it is always updated</title>
       <script src="jquery.min.js"></script>
       <script>
    
       </script>
    </head>
    <body>
       <img src="images/black.png" id="square" />
       <div>
          <button id="red-btn">Red</button>
          <button id="green-btn">Green</button>
          <button id="blue-btn">Blue</button>
       </div>
    </body>
    </html>
  2. Within the directory where the recipe-8.html file is created, create another directory called images and within this, add four images given as follows:

    • black.png

    • red.png

    • blue.png

    • green.png

  3. Add the following JavaScript within the <script></script> tags of recipe-8.html:

    $(function(){
       //Listen for a click on the red button
    $('#red-btn').click(function(){
       //When the red button has been clicked, change the source of the #square image to be the red PNG
       $('#square').prop("src", "images/red.png");
    });
       //Listen for a click on the green button
    $('#green-btn').click(function(){
       //When the green button has been clicked, change the source of the #square image to be the green PNG
       $('#square').prop("src", "images/green.png");
    });
    //Listen for a click on the blue button
    $('#blue-btn').click(function(){
       //When the blue button has been clicked, change the source of the #square image to be the blue PNG
       $('#square').prop("src", "images/blue.png");
    });
    });
  4. Opening this web page within a browser will allow you to change the source of the displayed image from the default black.png to another source depending on which button is clicked.

How it works…

To change the source of an image, we can use jQuery's prop() function and specify the new image name for the src property. To do this, when either of the buttons created using our HTML code are clicked, a click event handler is attached for each button using .click(), referencing the buttons' IDs, and then within the click() callback function,.prop() is executed with the appropriate image source specified, shown as follows:

$(function(){
$('#red-btn').click(function(){
   $('#square').prop("src", "images/red.png");
});

$('#green-btn').click(function(){
   $('#square').prop("src", "images/green.png");
});

$('#blue-btn').click(function(){
   $('#square').prop("src", "images/blue.png");
});
});

There's more...

This recipe illustrates the way a jQuery developer can easily change an image's source using a very simple example. A more realistic situation where this implementation will be used is within a web application where an image can be uploaded, for example, when a user chooses their avatar.

Traditionally, a user will be presented with a preview of their current avatar and then be able to choose an image from their computer to upload. Using AJAX, the web page can send this new image to the server; the server can then process and save this image and respond to the client web page. The web page, using jQuery's prop() method, can then update the current preview with the newly uploaded image and create a seamless transition without the need for the page to be refreshed in order to display the new image.

A problem occurs when the server uses the same filename for the new image as the old one. This is often the case when a user can only have one avatar; for the sake of simplicity, the avatar image is then saved using the user's unique ID (for example, 123.png).

When the server responds to the client with the new image filename, as the filename is the same, the browser will think that it is the same image. This may cause the browser to use the cached version of the avatar image, which will be the old image. To prevent this from happening, we can prepend a timestamp onto the image's filename. This will make the browser treat the image as new and force it to load the new image. We can modify the previous JavaScript to achieve the following:

$(function(){
$('#red-btn').click(function(){
     $('#square').prop("src", "images/red.png?t=" + new Date().getTime());
});

$('#green-btn').click(function(){
     $('#square').prop("src", "images/green.png?t=" + new Date().getTime());
});

$('#blue-btn').click(function(){
     $('#square').prop("src", "images/blue.png?t=" + new Date().getTime());
});
});

Using JavaScript's new Date() method, we create a new date that will be equal to the current date and time equal to the current time in milliseconds. We then use .getTime() to return a timestamp in milliseconds. When the source is updated, it will look as follows:

<img src="images/red.png?t=1371992012690" id="square">

This code will force the browser to reload the image using the newly specified source, provided the user does not update their image within the same millisecond (practically impossible).

 

Populating list elements


List elements are commonly used around the Web; they can be used to display search results, menus, and navigational items to name a few. Thanks to CSS, they no longer need to be boring, and it is possible to style list elements to make your data beautiful.

With jQuery, it is possible to populate a list element dynamically. This can be done directly from a JavaScript array via an AJAX response, with data from a web server or some other source.

Getting ready

Create a blank HTML document named recipe-9.html, and ensure that it is saved to a location where the latest version of jQuery can be included.

How to do it…

Learn how to dynamically populate a list with jQuery by performing each of the following recipes:

  1. In order to demonstrate how you can use jQuery to populate a list element, we will create a JavaScript array of objects. Add the following HTML and JavaScript code to recipe-9.html, which you have just created:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Populating list elements</title>
       <script src="jquery.min.js"></script>
       <script type="text/javascript">
          var names = [
             {
                id: 1,
                firstname: 'Leon',
                lastname: 'Revill'
             },
             {
                id: 2,
                firstname: 'Allyce',
                lastname: 'Wolverson'
             },
             {
                id: 3,
                firstname: 'Harry',
                lastname: 'Round'
             },
                {
                   id: 4,
                   firstname: 'Chris',
                   lastname: 'Wilshaw'
                }
             ];
             $(function(){
    
          });
       </script>
    </head>
    <body>
        <ul id="namelist"></ul>
    </body>
    </html>

    Note

    At the top of our JavaScript code, we have created an array of objects which includes a set of names. We are going to use this array to populate the list element #namelist within the HTML code.

  2. Add the following JavaScript within $(function(){});, just under the JavaScript array. This JavaScript will use the objects within the JavaScript array we created in the Getting ready section to populate the list element on our page.

    $.each(names, function(index, obj){
    $('#namelist').append("<li>#" + obj.id + " " + obj.firstname + " " + obj.lastname + "</li>");
    });

How it works…

We use jQuery's $.each() function to loop through each of the JavaScript objects within the names array. Then, for each of these objects, we can create a <li> element and insert the values of the id, firstname, and lastname variables. Finally, we can use the jQuery append() function to append the list element to the end of the unordered list.

Within the $.each() function, the first parameter is the array we wish to iterate through and the second parameter is the function we wish to execute for each of the objects within the names array. The specified function also has two arguments: index and obj. The index argument will contain the current array index of the JavaScript object, and the obj variable will contain the actual JavaScript object. Both these variables are available within the specified callback function.

We are then able to reference obj.propertyName (replace propertyName with a property of the object) in order to access specific parts of the object we wish to use. By doing this, we construct a string and pass it to the append() function, which then appends it to the specified #nameslist unordered list.

Open the HTML page within the browser, and you should see the list populated with the names from the JavaScript array, illustrated as follows:

See also

  • Creating DOM elements

  • Re-using DOM elements

 

Understanding pagination


Pagination is the act of collating large amounts of data and presenting it to the user in small, easy-to-read sections or pages.

With a combination of jQuery, JavaScript functions, and event handlers, we are able to easily collate and present data to the user in pages.

Getting ready

To create a paginated set of data, we first need some data to paginate and then a location to place the paginated data. Use the following code to create an HTML page:

<!DOCTYPE html>
<html>
<head>
   <title>Chapter 1 :: DOM Manipulation</title>
   <script src="jquery.min.js"></script>
   <script>
      var animals = [
         {
            id: 1,
            name: 'Dog',
            type: 'Mammal'
         },
         {
            id: 2,
            name: 'Cat',
            type: 'Mammal'
         },
         {
            id: 3,
            name: 'Goat',
            type: 'Mammal'
         },
         {
            id: 4,
            name: 'Lizard',
            type: 'Reptile'
         },
         {
            id: 5,
            name: 'Frog',
            type: 'Amphibian'
         },
         {
            id: 6,
            name: 'Spider',
            type: 'Arachnid'
         },
         {
            id: 7,
            name: 'Crocodile',
            type: 'Reptile'
         },
         {
            id: 8,
            name: 'Tortoise',
            type: 'Reptile'
            },
            {
               id: 9,
               name: 'Barracuda',
               type: 'Fish'
            },
            {
               id: 10,
               name: 'Sheep',
               type: 'Mammal'
            },
            {
               id: 11,
               name: 'Lion',
               type: 'Mammal'
            },
            {
               id: 12,
               name: 'Seal',
               type: 'Mammal'
            }
         ];
      var pageSize = 4;
      var currentPage = 1;
      var pagedResults = [];
      var totalResults = animals.length;
      $(function(){
   });       
   </script>
</head>
<body>
   <ul id="list"></ul>
   <button class="previous"><< Previous</button>
   <button class="next">Next >></button>
</body>
</html>

Within the JavaScript in this page, we have declared a large array of objects named animals, which represents a set of animals. Below this array, we have declared four more variables, which we will require in order to paginate the animals array:

  • pageSize: This indicates the amount of results we wish to be held on a single page

  • currentPage: This indicates the current page that is being displayed

  • pagedResults: This indicates an array that contains a section of the animals array, which represents the page

  • totalResults: This indicates the number of objects within the animals array; in this case, 12

How to do it…

To create a dynamic list with pages, perform each of the following steps:

  1. Directly after $(function(){}); but still within the <script></script> tags, add the following JavaScript function:

    function updateList() {
    //Grab the required section of results from the animals list
    var end = (currentPage * pageSize);
    var start = (end - pageSize);
    pagedResults = animals.slice(start, end);
    //Empty the list element before repopulation
    $('#list').empty();
    
    //Disable the previous button if we are on the first page
    if (currentPage <= 1) {
       $('.previous').prop("disabled", true);
    }
    //Enable the previous button if we are not on the first page
    else {
       $('.previous').prop("disabled", false);
    }
    
    //Disable the next button if there are no more pages
    if ((currentPage * pageSize) >= totalResults) {
       $('.next').prop("disabled", true);
    }
    //Enable the next button if there are results left to page
    else {
       $('.next').prop("disabled", false);
    }
    
    //Loop through the pages results and add them to the list
    $.each(pagedResults, function(index, obj){
       $('#list').append("<li><strong>" + obj.name + "</strong> (" + obj.type + ")</li>");
    });
    }
  2. Add the following JavaScript within $(function(){}); in the preceding HTML page:

    //Populate the list on load
    updateList();
    $('.next').click(function(){
    //Only increase the current page if there are enough results
    if ((currentPage * pageSize) <= totalResults) currentPage++;
    updateList();
    });
    
    $('.previous').click(function(){
    //Only decrease the current page if it is currently greater than 1
    if (currentPage > 1) currentPage--;
    updateList();
    });

How it works…

Although pagination can seem quite complicated, in principle, it is simple. We will need to use jQuery's click() function to listen for click events on the next and previous buttons. When these buttons are pressed, the currentPage variable is either incremented or decremented based on which button is clicked. After this, the updateList() function takes the currentPage value, works out which section of data it needs to use from the animals array, populates the pagedResults array with this data, and then loads these results into the HTML list element, #list.

Additionally, we will need to disable the next or previous buttons depending on which page the user is currently viewing. If they are currently viewing the first page, the previous button can be disabled using jQuery's prop() function to set its disabled property to true. If the user is viewing the last page (which our function can work out using the totalResults, currentPage, and pageSize variables), we need to disable the next button.

//Populate the list on load
updateList();
$('.next').click(function(){
//Only increase the current page if there are enough results
if ((currentPage * pageSize) <= totalResults) currentPage++;
updateList();
});

$('.previous').click(function(){
//Only decrease the current page if it is currently greater than 1
if (currentPage > 1) currentPage--;
updateList();
});

To expand on the well-commented code, the first thing we do is call a function named updateList(), which we will look at a little later in this recipe.

Note

Remember that any code within $(function(){}); is executed on page load.

Next, we attach a click event handler to the next button by passing a callback function as an argument. For this event function, we are able to specify some code to be executed every time the next button is clicked. The code we specify increments the currentPage variable by 1. If there is another page of data available, it works this out by forming the ((currentPage * pageSize) <= totalResults) condition as part of the if statement.

Finally, as a part of this click function, we call the previously mentioned updateList() function.

We apply the same logic to the previous button also, except that we are decrementing the currentPage value if the current page is greater than one; hence, there is a page to go back to.

Below $(function(){}); but still within the <script></script> tags, add the following JavaScript function to your HTML page:

function updateList() {
//Grab the required section of results from the animals list
var end = (currentPage * pageSize);
var start = (end - pageSize);
pagedResults = animals.slice(start, end);
//Empty the list element before repopulation
$('#list').empty();

//Disable the previous button if we are on the first page
if (currentPage <= 1) {
   $('.previous').prop("disabled", true);
}
//Enable the previous button if we are not on the first page
else {
   $('.previous').prop("disabled", false);
}

//Disable the next button if there are no more pages
if ((currentPage * pageSize) >= totalResults) {
   $('.next').prop("disabled", true);
}
//Enable the next button if there are results left to page
else {
   $('.next').prop("disabled", false);
}

//Loop through the pages results and add them to the list
$.each(pagedResults, function(index, obj){
   $('#list').append("<li><strong>" + obj.name + "</strong> (" + obj.type + ")</li>");
});
}

To maintain good practices, the code is well-commented once again. The first action that this function performs is calculating which section of the animals array it needs to use. Once it has calculated the start and end values, which are index values for the animals array (for example, 0 to 4 for page one), it uses JavaScript's slice() function to copy this data from the animals array to the pagedResults array.

Note

Be careful to not use the similar, JavaScript's .splice() function as this will actually remove the data from the animals array as well as copy it to the pagedResults array. Additionally, slice() takes two arguments: the first is a zero-indexed number stating the start location of the array (that is, 0 is the beginning), and the second argument is not the location within the array but the number of elements from the starting point.

With the required results stored in the pagedResults array, it uses jQuery's empty() function to empty the unordered list, #list, of any data. This is to prepare the list for repopulation. Otherwise, when the next or previous button is clicked and the updateList() function is run, the results will just get appended to the end of the current list and not replaced.

The next section of code is to determine if the next and previous buttons need to be either disabled or enabled. We can work out whether the previous buttons need to be disabled by putting the condition (currentPage <= 1), which simply checks to see if the current page is less than or equal to one; if it is, we need to disable the previous button; otherwise, we need to enable it. This is done using jQuery's prop() function, which allows us to manipulate the properties on selected elements; here, we change the disabled property to either true or false. We can determine whether we need to disable the next button using ((currentPage * pageSize) >= totalResults), which calculates whether there are enough objects within the animals array to create the next page; if there are not, we disable the button, but if there are, we enable it.

Finally, we use jQuery's $.each() function to iterate through each of the objects within the pagedResults array and append a list element with the data from each object to the unordered list on the page.

If you open the HTML page within the browser, you should see a similar page to the one illustrated as follows:

On page load, the list is populated with the first page of results, as currentPage is set to 1 and the updateList() function is also set to run on page load, which disables the previous button.

 

Removing DOM elements


jQuery makes it easy for the developer to completely remove DOM elements, which is often useful when creating rich user interfaces. Having the ability to remove elements is useful in situations where your interface represents some information from a database, and it provides a way for the user to delete database items. If this UI is using AJAX to send the delete request to the web server, you will need to reflect the delete action on the client side and remove the element representing the database item.

Getting ready

Create a blank HTML document, and save it as recipe-11.html to an easily accessible location on your computer.

How to do it…

Understand how to remove DOM elements using jQuery by performing each of the following steps:

  1. Add the following HTML code to the recipe-11.html page you have just created:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Removing DOM elements</title>
       <script src="jquery.min.js"></script>
       <script>
    
       </script>
    </head>
    <body>
       <ul id="list">
          <li>Item 1 <button class="remove-btn">X</button></li>
          <li>Item 2 <button class="remove-btn">X</button></li>
          <li>Item 3 <button class="remove-btn">X</button></li>
          <li>Item 4 <button class="remove-btn">X</button></li>
       </ul>
    </body>
    </html>
  2. Within the <script></script> tags of the previous HTML document, add the following JavaScript code:

    $(function(){
    //Listen for a click on any of the remove buttons
    $('.remove-btn').click(function(){
       //When a remove button has been clicked
       //Select this buttons parent (the li element) and remove it
       $(this).parent().remove();
    });
    });
  3. Open the HTML document in a browser and click on the remove button to remove the selected list item.

How it works…

jQuery provides us with a remove() function, which will remove the selected element from the DOM. In a situation as the one mentioned previously, you would have a list of items that represent the records within the database. Each of these list items would provide a remove button, allowing the user to delete the selected item.

In a real-world situation, this delete button would make an AJAX request to a web server, wait for the response, and then remove the selected element on the client side. To keep this recipe simple, we will just be looking at the JavaScript code to remove the element on the client side and will not be working with AJAX.

Note

Chapter 3, Loading and Manipulating Dynamic Content with AJAX and JSON, contains a wealth of AJAX recipes.

We can use jQuery's click() function to listen for a click event on one of the delete buttons. Then, we can use $(this).parent() to select the <li> element we wish to delete, because the delete button is a sibling of this list element. We can then use the remove() method with no arguments to remove the selected list element.

See also

  • Creating DOM elements

  • Re-using DOM elements

 

Re-using DOM elements


When using jQuery to dynamically create elements such as list items, divisions, and input, it can be useful to be able to re-use these elements without having to rewrite them within JavaScript. Instead, it may be beneficial to copy the elements and just modify the sections you wish to change.

Getting ready

Using the text editor of your choice, create a blank HTML document named recipe-12.html, which is within a location that has easy access to the latest version of jQuery.

How to do it…

Learn how to re-use DOM elements by performing each of the following recipe steps:

  1. Within the recipe-12.html page you have just created, add the following HTML, CSS, and JavaScript code:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Reusing DOM elements</title>
       <style type="text/css">
          .one {
             background-color: #CCC;
             color: #333;
          }
          .two {
             background-color: lawngreen;
             color: white;
          }
          .three {
             background-color: darkgreen;
             color: white;
          }
          .four {
             background-color: black;
             color: #666;
          }
          .dinosaur {
             background-color: darkred;
             color: red;
          }
       </style>
       <script src="jquery.min.js"></script>
       <script>
          var animals = [
             {
                id: 1,
                name: 'Dog',
                type: 'Mammal',
                class: 'one'
             },
             {
                id: 2,
                name: 'Cat',
                type: 'Mammal',
                class: 'one'
             },
             {
                id: 3,
                name: 'Goat',
                type: 'Mammal',
                class: 'one'
             },
             {
                id: 4,
                name: 'Lizard',
                type: 'Reptile',
                class: 'two'
             },
             {
                id: 5,
                name: 'Frog',
                type: 'Amphibian',
                class: 'three'
             },
             {
                id: 6,
                name: 'Spider',
                type: 'Arachnid',
                class: 'four'
             }
          ];
          $(function(){
    
          });
       </script>
    </head>
    <body>
    <ul id="animal-list">
       <li class='dinosaur'><strong><span class='name'>T-Rex</span></strong> <span class='type'>Dinosaur</span></li>
    </ul>
    </body>
    </html>
  2. Within the HTML page you created from the preceding code, add the following JavaScript within $(function(){});:

    $.each(animals, function(index, obj){
    //Clone the first element in the animal list
    var listTemplate = $('#animal-list li').first().clone();
    //Change its name to match this objects name
    listTemplate.find('.name').html(obj.name);
    //Changes its type to match this objects type
    listTemplate.find('.type').html(obj.type);
    //Remove all its current classes
    listTemplate.removeClass();
    //Add the class from this object
    listTemplate.addClass(obj.class);
    //Append the modified element to the end of the list
    $('#animal-list').append(listTemplate);
    });
  3. If you open your newly created web page within a browser, you should be provided with a populated list element that matches the objects within the JavaScript array animals.

How it works…

By using jQuery's $.each() method, we are able to iterate through each of the objects within the JavaScript animals array. Then, for each of the JavaScript objects, we clone the first element in the unordered list using $('#animal-list li').first().clone(); and store it within the listTemplate variable. This variable now holds a copy of the first list element within the unordered list #animal-list. We can now manipulate this element as we would do with any other DOM element. We are able to use jQuery's find() function to locate the span elements with the .name and .type class names. We can then alter their content to match the current object's name and type values. Next, we remove the previous styles on the cloned element with removeClass() (not providing an argument will remove all current classes without having to specify each one of them), and add the style that is specified within the JavaScript object using the addClass() function that jQuery provides us with. Finally, we can append the modified HTML element to the end of the list using append().

See also

  • Removing DOM elements

  • Creating DOM elements

About the Author
  • Leon Revill

    Leon Revill has over three years of commercial AngularJS development experience and is currently working as a Mobile Architect building complex mobile platform applications using AngularJS and other modern web technologies. As an AngularJS mentor at Thinkful, he tutors students all around the world, taking them from AngularJS novices to ninjas in just a few months. Leon is also interested in writing free articles and tutorials covering a wide range of web development topics via his blog http://www.revillweb.com.

    Browse publications by this author
jQuery 2.0 Development Cookbook
Unlock this book and the full library FREE for 7 days
Start now