Exercise Answers - Appendices - Web Development with jQuery (2015)

Web Development with jQuery (2015)

Part IV. Appendices

Appendix A. Exercise Answers

Chapter 2

1. CSS and XPath are both acceptable answers.

2. parents()

3. prev()

4. children() for immediate descendants and find() for any elements in the descendant hierarchy

5. not()

6. eq()

7. siblings(), prev(), next(), prevAll(), nextAll()

8. add()

Chapter 3

1. You can use the mouseover() or on('mouseover') method. If you use deprecated methods, in addition, you can use bind('mouseover') or live('mouseover').

Extra Credit: Use the hover() method.

2. The on() method.

3. The event.target property is used to check to see which descendant element has received the event. The event then bubbles up from that element to the element that the event handler is attached to.

4. Provide a selector argument to the on() method describing the element you want the event to apply to on the parent or container element that contains the elements you want the event to apply to. This can also be the document object.

5. Naming an instance of an event handler can be done by applying the event name, a dot, and then the namespace you want to use. You can apply multiple event names by repeating the same process.

6. The off() method.

7. Yes.

8. You can use either click() with no arguments or trigger('click').

9. A custom event handler begins with any event name not already in use in JavaScript; you can attach a custom event handler using that name using the on() method. The trigger() method can be used to fire the custom event handler, as well as to send custom data to the event handler.

Chapter 4

1. One possibility:

2. $('input').attr(

3. 'value' : 'Some Value'.

4. 'class' : 'someClass'


Another possibility:

$('input').addClass('someClass').val('Some Value');

5. It might look like this:

$('a').attr('href', 'http://www.example.com');

6. removeAttr()

7. hasClass()

8. No, HTML tags will not be present in the return value, only the element's text content.

9. Yes, HTML tags will be escaped and treated like text content.

10.One bug that jQuery's append() and prepend() methods work around in IE is how IE makes innerHTML Read Only on <table> elements.

11.One bug that jQuery's append() and prepend() methods work around in Firefox is how Firefox occasionally loses form input values when appending or prepending HTML content using innerHTML.






Chapter 5

1. It might look like this:

2. $(nodes).each(

3. function() {

4. }

5. );

6. $.each(

7. nodes,

8. function() {

9. }


10.return false;

11.The items referenced by the selector are kept in the selection; items not referenced by the selector are discarded.

12.Keeps the current item in the selection; returning false removes the current item from the selection.

13.A value that evaluates to true. Returning false will remove an item from the array.

14.It replaces the value of the item passed to the callback function during that iteration.

15.–1 means that the value does not exist within the array; a return value of zero or greater means that the value exists within the array.

Chapter 6

1. $('div').css('color');

2. Specifying any color in the second argument, the code would look something like this:

$('body').css('backgroundColor', 'yellow');

3. $('div').css({

4. padding: '5px',

5. margin: '5px',

6. border: '1px solid grey'

7. });


9. outerWidth()


Chapter 7

1. In the context of an AJAX request, the only difference between GET and POST requests is that a GET request has a concrete limitation on the amount of data you can pass; the actual limit varies from browser to browser. A GET request can also be slightly more efficient.

2. A REST service implements more meaning in HTTP requests by providing additional methods that describe data manipulation, such as ADD or DELETE. In addition, a REST service may also be implemented to standardize server responses so that they utilize the proper HTTP error codes.

3. An optional second argument to the $.get() method allows you to pass data along with the request, either as a query string or as a JavaScript object literal.

4. You access the JSON object in the variable that you assign to the first argument of the callback function that you specify for the $.getJSON() method. This variable can have any name you like.

5. Accessing the contents of the <response> element looks something like this:

6. $.get(

7. '/url/to/request.xml',

8. function(xml)

9. {

10. alert($(xml).text());

11. }


12.The load() method.

13.In the JavaScript, jQuery sets AJAX events globally via a call to the $.ajaxSetup() method, which takes a list of options that are formatted as a JavaScript object literal. The beforeSend property specifies a callback function that is executed before every AJAX request. The success property specifies a callback function that is executed upon every successful AJAX request. The error property specifies a callback function that is invoked upon encountering an HTTP error. Finally, the complete callback function is executed when the request has completed, after the success or error callbacks have been executed, depending on whether the request was successful.

14.One method is by using jQuery's AJAX event methods like ajaxStart() and ajaxSuccess(); another is via jQuery's $.ajax() method.

15.Select the form elements you want to get the values of; then call the serialize() method.

16.You use the type property to set the request method to DELETE. You use the contentType property to set the MIME type of the request to signal to the server that the body of the request is a JSON object. Then you pass the JSON data to send in the body of the request within the data property. An example of creating this call using the $.ajax() method follows:


url : '/Server/Example',

contentType : "application/json; charset=utf-8",

type : 'DELETE',

dataType : 'json',

data : JSON.stringify({

dataForTheServerHere : true


success : function(json, status, request)



error : function(request, status)




Chapter 8

1. An integer value in milliseconds or the strings 'slow', 'normal', or 'fast'.

2. It animates an element's height property when displaying an element.

3. The fadeIn(), fadeOut(), and fadeToggle() methods all animate an element's opacity to display or hide an element.

4. The animate() method.

5. The linear and swing easings are included in jQuery core.

Chapter 9

1. $.fn.extend() or $.fn.prototype.

2. console.log($.fn); Then examine the object in Firefox or Chrome.

3. Define my functions or objects inside the closure used to define my plugin.

4. They are defined in the keyword this.

5. It should attempt to return this (the selection in context), or jQuery, if possible.

6. It allows me to remove my own events explicitly, without touching other people's or other projects' events.

7. Answers may vary but include any valid code that meets the specified criteria.

Chapter 10

1. scrollTop() and scrollLeft().

2. The top (or offset top) of the wanted element, the top (or offset top) of its container, and the current vertical scrollbar position (or scrollTop).

3. Any syntactically correct code implementing something similar to the following:


4. Answers will vary but should describe calculating the element's scrollHeight and using an arbitrary value expected to be larger than the scrollHeight.

5. 0.

Chapter 11

1. Depending on the browser, you use the –webkit-user-drag CSS property with a value of element for older versions of Webkit-based browsers such as Safari and Chrome. You use the draggable HTML attribute, which is the official method sanctioned by the HTML5 specification and supported by all modern browsers. Or you can use the dragDrop() method on the element's DOM object, which enables drag and drop in IE5 through IE8.

2. The drag events in the order that they fire are dragstart, drag, and dragend.

3. The drop events in the order that they fire are dragenter, dragover, drop, and dragleave.

4. You look for event.originalEvent.dataTransfer.files within the drop event. Without using jQuery to attach the event listener, you look for event.dataTransfer.files within the drop event.

5. A base64-encoded data URI is assigned to the value of the src attribute of an <img /> element. The data URI can also be used with the CSS background and background-image properties.

6. The progress and load events can be attached to the upload property of an XMLHttpRequest object to monitor the upload progress of files.

7. The event.lengthComputable, event.loaded, and event.total properties.

8. First, you instantiate the FormData object; the instantiated object is stored in a variable. Then use the append() method on the instantiated object to create custom POST variables.

9. You attach a load event to the XMLHttpRequest object. This event is fired when the upload is successful.

Chapter 12

1. draggable()

2. Any syntactically correct program, which implements the following (or similar enough to the following):

3. draggable({

4. helper : 'clone',

5. opacity : 0.5

6. });

7. droppable()

8. Any syntactically correct program implementing something similar to this:

9. droppable({

10. hoverClass : 'theHoverClassYouUsed'

11. });

12.You would use the accept option, and the value that you provide to the accept option would be a valid selector.

Chapter 13

1. The sortable() method.

2. A CSS class name that will be applied to the placeholder.

3. It creates blank space within a sortable list that represents a reservation for the item currently being dragged during a sort.

4. The cursor option.

5. It allows you to create a custom drag image for the element being dragged during a sort; this drag image is also known as the helper.

6. The connectWith option.

7. A selector, a selection, an element, or a callback function that returns an element or selection.

8. By providing a callback function to the update event, which contains logic that sends an AJAX request to a server-side script.

Chapter 14

1. The start option.

2. The selecting and unselecting options.

3. The added elements are accessed from the ui.selecting selector, and the removed elements are accessed from the ui.unselecting selector.

4. div.ui-selectable-helper

Chapter 15

1. The active option.

2. The heightStyle option with the values auto, fill, or content.

3. The event option with the value mouseover.

4. The header option with the value h3.

Chapter 16

1. The minDate and maxDate options.

2. The yearRange option. Example value: “1900:2020”

3. The changeMonth and changeYear options.

4. The dateFormat option.

5. Yes. By providing an array of the Spanish translated weekdays to the dayNames, dayNamesMin, or dayNamesShort options.

6. Use the firstDay option to provide the starting day of the week. Sunday is number 0 and Saturday is number 6. For example, to change the starting day to Tuesday, you would set firstDay : 2.

Chapter 17

1. The modal option with positioning the <div> with class name ui-widget-overlay. It must be positioned to take up the entire window in front of the document's content but behind the opened dialog.

2. Set the autoOpen option to false.

3. By calling dialog('open').

4. By calling dialog('close').

5. By setting the draggable and resizing options to false.

6. The show option with an animation preset such as 'explode'.

Chapter 18

1. The active tab with a value indicating the tab to display, offset from zero.

2. The class names are ui-tabs-active and ui-tabs-hover.

3. Add a new tab that references the content you want to load in the href attribute of the <a> element. The jQuery Tabs plugin takes care of the rest.

4. The show and hide options.

Chapter 19

1. No sorting occurs until you explicitly sort by a header unless you specify the sortList option, which specifies how default sorting should be handled.

2. You would use the sortMultiSortKey option with the value 'ctrlKey'.

3. You use the cssHeader, cssAsc, and cssDesc options to specify custom class names.

Chapter 20

1. You must keep track of whether the slideshow has been interrupted to prevent the normal transition from occurring.

2. The transitioning property prevents multiple animations from occurring simultaneously. It ensures that only one animation happens at a time.

3. The number of items with the slideshow element with the class name slide is iterated, and controls are created for each of these items. The controls are given an id name that contains a reference to the collection and a reference to the slide. Finally, the slide's offset number is made the text of the control.

Chapter 21

1. <audio> and <video>

2. <source>

3. h.264, Ogg, and WebM

4. The tracks option. (Extra credit for specifying that it displays the text from HTML5 <track> elements.)

5. The preload attribute.

Chapter 22

1. contenteditable

2. document.execCommand

3. Any options that require a user interface prompt or data value when used with document.execCommand, such as fontname or fontsize.

4. Answers will vary but should describe a Selection object that contains a collection of Range objects, which, in turn, stores information about bounding nodes and positions within them.

5. $(this).data()