Marakana jQuery Training

v1.5, September 2012: Updating to jQuery 1.8

Introduction To JQuery

In this chapter, we are going to discuss why learning about jQuery is a good investment, what are its strength, competitive advantages to other JavaScript libraries out there and what are the advantages of using jQuery rather than pure JavaScript

We are also going to discuss about how to start with jQuery (discussing about where to get the library, how to be "ready" to use it in your web pages and where to look for useful complementary learning resources)

   Useful Learning Resources

   History Of JQuery

Aug. 22, 2005

Everything started here where John Resig, creator of jQuery, showed us a few ideas of what would become jQuery(http://ejohn.org/blog/selectors-in-javascript/)

Jan. 14, 2006

jQuery announced

Jan. 24, 2006

Creation of the jQuery Blog

Jan. 27, 2006

Creation of the jQuery mailing list

Aug. 26, 2006

First stable version of jQuery, v1.0 released

Jan. 14, 2007

Anniversary of jQuery. v1.1 released: significant performance improvements; reduced, simplified API

Sep. 10, 2007

v1.2 released: additional DOM traversal and manipulation methods; improved animation control; JSONP support; XPath selectors removed

Sep. 17, 2007

First version of jQuery UI released: fully themed interaction and widget library built on top of jQuery

Jan. 14, 2009

Third anniversary of jQuery. v1.3 released: CSS selector engine, Sizzle, available as a standalone component; "live event" binding; improved cross-browser event abstraction; significant performance improvements

Mar. 6, 2009

jQuery UI 1.7 released: ThemeRoller theme generation; new project hosting domain

Jan. 14, 2010

Fourth anniversary of jQuery. v1.4 released: more performance improvements; more DOM traversal and manipulation methods; more animation control; more moreness

Jan. 21, 2010

jQuery.org goes live (site containing resources for jQuery and related projects)

Mar. 23, 2010

jQuery UI 1.8 released: new utilities; new widgets; upgraded widget factory; more modular core

Jan. 31, 2011

v1.5 released: deferred objects; improved, extensible Ajax support

May. 3, 2011

v1.6 released: major rewriting of the attribute module; performance improvements

Nov. 3, 2011

1.7 released: .on and .off become preferred event binding mechanisms

Aug. 9, 2011

1.8 released: smaller and faster code size - Sizzle selector engine rewritten, animation support improved and cleaned up, css prefixing supported automatically.

2013?

1.9 and 2.0 released. 1.9 will be the last version that supports IE 6/7/8


Note At the time of this writing, the latest version of jQuery is v1.6.4 which has been released in September 12th, 2011.

   What is JQuery?

   JQuery vs Custom JavaScript


John Resig, creator of jQuery, gave an interesting talk at Yahoo addressing browser inconsistencies: "The DOM is a mess" (http://ejohn.org/blog/the-dom-is-a-mess/)

   JQuery vs Other JavaScript Libraries

images/introduction_google_trends.png

   Where Do I Start?

   Download the Library


Warning

Some browsers do not handle “self-closing” <script> tags correctly. For example, some browsers fail to load the script if you use the following syntax:

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

To ensure proper loading of your script, alway use an explicit close tag, like this:

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

   Using Google Content Deliver Network (CDN)

Tip

When loading jQuery from CDN, your src attribute can omit the patch level in the URL, in which case you automatically load the most recent version of that minor release of jQuery. For example:

<script type="text/javascript"
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

   The jQuery Function Object


Many other JavaScript libraries, such as Prototype, also use $ as a function or variable name. If you need to use one of the libraries in conjunction with jQuery, you can have jQuery relinquish the $ alias by executing:

jQuery.noConflict();

   Is The Document Ready?


Note Observe that we are actually providing a reference to an anonymous function as the argument to the ready() method.

   Where to Run Your Code?

   Execute Some JQuery Code


Note After you have observed the effect of this jQuery script, you can revert yamba1.html to its original state. The highlight effect shown is not used in subsequent exercises.

Of course, the result of this simple script could be achieved more easily just by editing your document’s CSS, rather than running jQuery code. The advantage of jQuery will become more apparent as we create more complex and dynamic effects.

   Introduction To JQuery: Exercises

Questions

  1. Are these statements the same:

    <script src="libs/jquery-1.6.4.js"></script>
    <script src="libs/jquery-1.6.4.js" />
  2. What are pros and cons of including jQuery at top of the page versus bottom?

Labs

Download the lab files at http://marakana.com/static/student-files/jquery_labs.zip if you have not done it yet

For these labs, start with the file labs/yamba1.html. It includes a <script> element to load a file named introduction.js, which you should edit in the labs directory.

  1. Write code that will check if the document is ready, and then alert the user. Do this using the “long” syntax.

  2. Update the code you wrote to check if the document was ready with the “short” syntax.

Selection and DOM Traversal

Before you start doing any interactions with your page you need to select one or more elements in your page.

This chapter will illustrate different ways to select elements on your page.

You will also learn jQuery techniques for traversing the document object model (DOM) — that is, finding parent elements, siblings, etc. from an original selection.

   Selection

   Basic Selectors

Basic jQuery selectors work the same as CSS selectors:

$('p');

Selects all the <p> elements in your page

$('*');

Selects all elements on the page

$('.status');

Selects all elements with the class status

$('#header');

Selects the element with the id header

Note You should not use the same id for more than one element. If you do so and if you perform a selection by id, only the first matched element in the DOM will be returned
$('p, li, .status, #nav');

Selects all <p> and <li> elements, all elements with the status class, and the element with the id nav.

   Hierarchy Selectors

JQuery hierarchical selectors also work the same as CSS selectors:

$('#footer span');

Selects the <span> elements that are descendants of the element with the id footer.

$('ul > li');

Selects the <li> elements that are immediate children of <ul> elements.

$('h2 + p');

Selects the <p> elements that are immediately preceded by an <h2> element.

$('h2 ~ p');

Selects all <p> elements following an <h2> element that have the same parent as the <h2> element.

   Selection By Attribute

Another powerful selection type is selection by attribute:

$('a[href]');

Selects all <a> elements that have an href attribute.

$('a[href="http://mrkn.co/f/271"]');

Selects all <a> elements whose href attribute exactly matches "http://mrkn.co/f/271".

$('a[href*="goo.gl"]');

Selects all <a> elements whose href attribute contains "goo.gl". For example, this would match:

<a href="http://goo.gl/DeSyV" class="url">Interesting link</a>
$('a[href^="http://bit.ly"]');

Selects all <a> elements whose href attribute starts with "http://bit.ly". For example, this would match both of these elements:

<a href="http://bit.ly/eU3ccR" class="url">One link</a>
<a href="http://bit.ly/jqcon11SF" class="url">Another link</a>
$('a[href$=".pdf"]');

Selects all <a> elements whose href attribute ends with ".pdf". For example:

<a href="http://mrkn.co/docs/info.pdf" class="url">Download PDF version</a>
$('p[lang|="en"]');

Selects all <p> elements whose lang attribute matches either "en" or "en-\*", where * can be anything.

Note A detailed explanation on selection by attribute can be found at the following URL: http://api.jquery.com/category/selectors/attribute-selectors/

   Form Selectors

jQuery also comes with useful selectors related to forms.

$(':button');
$(':checkbox');
$(':file');
$(':image');
$(':password');

$(':radio');

$(':reset');
$(':submit');
$(':text');

Selects all <input> elements of the specified type.

$(':input');

Selects all form elements, including <textarea> and <select> elements.

$(':checked');

Selects all checkbox and radio elements that are checked.

$(':selected');

For <option> elements, returns the selected option(s).

$(':disabled');
$(':enabled');

Selects all disabled/enabled form elements.

Note It’s recommended to precede these selectors with a tag name or some other selector; otherwise, the universal selector (*) is implied (e.g., $(":checkbox") implies $("*:checkbox")).

The following will serve as an example to demonstrate form selectors:

<form name="foodieform">
  <fieldset>
    <legend>Search a recipe:</legend>
    <label for="txt_recipe_name">Recipe name:</label>
    <input type="text" name="txt_recipe_name" id="txt_recipe_name" />
    <label for="meal_type">Type of meal:</label>
    <select id="meal_type" name="meal_type">
      <option value="Apetizer" selected>Apetizer</option>
      <option value="Entree">Entree</option>
      <option value="Drinks">Drinks</option>
      <option value="Desert">Desert</option>
    </select>
  </fieldset>
  <fieldset>
    <legend>Choose a type of food</legend>
    <input type="checkbox" name="food_type" value="French" checked>French</input>
    <input type="checkbox" name="food_type" value="Italian">Italian</input>
    <input type="checkbox" name="food_type" value="Mexican">Mexican</input>
    <input type="checkbox" name="food_type" value="Chinese">Chinese</input>
  </fieldset>
  <fieldset>
    <legend>Skills required</legend>
    <input type="radio" name="food_skills" value="1"/>Easy
    <input type="radio" name="food_skills" value="2"/>Medium
    <input type="radio" name="food_skills" value="3" checked/>Hard<br/>
  </fieldset>
  <input type="button" name="form-button" id="form-button" value="search"/>
  <input type="reset" name="form-reset" id="form-reset"/>
</form>
  • $(':checked'); would select:
    <input type="checkbox" name="food_type" value="French" checked>French</input>
    <input type="radio" name="food_skills" value="3" checked/>Hard<br/>
  • $(':radio'); would select:
    <input type=​"radio" name=​"food_skills" value=​"1">
    <input type=​"radio" name=​"food_skills" value=​"2">​
    <input type=​"radio" name=​"food_skills" value=​"3" checked>
  • $(':reset');:: Selects reset elements. In this case:
    <input type=​"reset" name=​"form-reset" id=​"form-reset">
  • $(':selected'); would select:
    <option value=​"Appetizer" selected>​Appetizer​</option>
  • $(':text'); would select:
    <input type=​"text" name=​"txt_recipe_name" id=​"txt_recipe_name">
Note More information on form selectors is available here ⇒ http://api.jquery.com/category/selectors/form-selectors/

   Position Filters

jQuery allows you to filter the elements selected based on their position in the collection. For example:

$('.article:eq(2)');

Selects the third element with the class article. Elements in a collection are numbered starting with 0.

$('.article:gt(1)');

From the collection of all elements with the class article, select all elements following the second one.

$('.article:lt(3)');

From the collection of all elements with the class article, select up to the first three.

$('.article:first');

Selects the first element with the class article

$('.article:last');

Selects the last element with the class article

$('.article:odd');

Selects the odd elements out of all the elements with the class article (zero-based index: 1,3,5,etc)

$('.article:even');

Selects the even elements out of all the elements with the class article (zero-based index: 0,2,4,etc)

Note The order of elements in a collection is determined by the order in which they appear in the document.

   Other Filters

Other useful jQuery filters include:

$(p:contains('Marakana'));

Selects all <p> elements that contain the string "Marakana", either directly or in any of the child elements. The text matching is case sensitive.

$('div:has(h2)');

Selects all <div> elements that have at least one <h2> element as a descendant.

$('option:not(:selected)');

Selects all <option> elements that are not selected.

$('p:hidden');
$('p:visible');

Selects all <p> elements that are hidden/visible. An element is considered hidden if:

  • It has a CSS display value of none
  • It is a form element with type="hidden"
  • Its width and height are explicitly set to 0
  • An ancestor element is hidden, so the element is not shown on the page

   jQuery Method Chaining

   DOM Traversal

   Filter Methods

   Advanced Method Chaining

   Selection and DOM Traversal: Exercises

For these labs, start with the file labs/yamba2.html. It includes a <script> element to load a file named
selections_and_dom_traversing.js, which you should edit in the labs directory.

Note

To get a visual result for each selection we made, we are going to use jQuery CSS styling. To apply a background color to a selection, execute:

<your selection>.css('backgroundColor','color');
  1. Select all but the first tweet and change the background color of those tweets to be yellow. See if you can come up with two different ways to accomplish this.

  2. Select the button element using form selectors and change the background color of this button to be yellow.

  3. Select all "bit.ly" links in tweets using attribute selectors and change their background color to be red. See if you can come up with two different ways to accomplish this.

  4. Post an alert reporting the number of <div> elements on the page.

  5. Add a dashed, black border of 1px to the profile image in each tweet.

    • You will have to apply the following CSS operations.
      <your selection>.css('borderWidth','1px');
      <your selection>.css('borderColor','black');
      <your selection>.css('borderStyle','dashed');

DOM And Attributes Manipulation

   DOM Manipulation

   Creating Elements

There are two ways to create elements in jQuery:


Some jQuery programmers follow a convention of using $ as the first character for variable names when those variables contain jQuery objects. Although this naming convention is not universal, we will follow it in this course.

   Inserting Elements

   Inserting an Element Before or After Another Element

Before an Existing Element

After an Existing Element

   Inserting an Element as the First or Last Child of a Parent

As the First Child

As the Last Child

   Mass Insertion

   Moving Elements

Note If the target selection contains more than one element, the elements being moved are duplicated and inserted into each target.

   Cloning (Copying) Elements

   Removing Elements

   Replacing Elements

   Element Content: HTML vs Text

Note Do not use the .text() method to get or set value for <input> elements. Use the .val() method instead

   Element Attributes And DOM properties

   DOM And Attributes Manipulation: Labs

For these labs, start with the file labs/yamba3.html. It includes a <script> element to load a file named
dom_manipulation.js, which you should edit in the labs directory.

Note

Here we are going to use the click event. Since we have not discussed event handling in detail yet, keep the following in mind for this lab:

  • You use the .click() method to register a function to be executed when the user clicks on an element:
    <your selection>.click(function(){ ... });
  • Within the handler function, use $(this) to refer to the object the user just clicked on.
  1. Let the user type in a new tweet. When the user clicks on the "Tweet" button, add that tweet to the top of the timeline by creating a new status line item.

  2. Repeat the previous lab, but this time try cloning an existing tweet and updating it with information for the new tweet.

  3. Let the user remove tweets by clicking on the X remove icon.

    Important You will notice that tweets that are added dynamically will not be removed when the user clicks on their remove icon. This is absolutely normal and this is a problem that we are going to fix in the labs for the events module.

CSS Styling and JQuery

   Reading And Modifying CSS Properties

   Reading And Modifying CSS Properties


When you use .css() to change a property, jQuery modifies the element’s style property. For example:

$('#mydiv').css('color', 'green');

is equivalent to:

document.getElementById('mydiv').style.color = 'green';
Note

You can use shorthand CSS properties (e.g., margin, background, border) only when setting properties. For example, jQuery supports:

$selection.css('border-left', '5px solid #ccc');

For retrieving property values, you must specify individual property names. For example, if you want to retrieve the rendered margin, use: $selection.css('marginTop'), $selection.css('marginRight'), and so on.

   Removing CSS Properties

   CSS Classes

Note For each of these methods, you may provide a space-separated list of class names.

   Element Dimensions


In contrast, the .css('height') and .css('width') methods return values with units intact (for example, "400px").

jQuery 1.4.1 and later allows you to provide a function as an argument to .height() and .width(). The function is invoked for each element in the selection, and it receives two arguments: the index position of the element in the set and the current height/width of that element. The function should return the new height/width for that element.

   Element Position

   CSS Styling and JQuery: Labs

For these labs, start with the file labs/yamba4.html. It includes a <script> element to load a file named css_styling.js, which you should edit in the labs directory.

  1. Select the second line of every status update (where it says the date it was posted) and make it smaller by 20%.

  2. Change the color of every other row to a slightly gray color (#efefef). Do this by modifying the CSS property of each matched status item.

  3. Change the color of every other row, but this time do it by adding the CSS class zebra to all the rows you want to be a different color.

    Note The zebra class is already defined in the external CSS file, yamba.css.
  4. Set the class of the current hovered tweet to zebraOver. Remove that class when the mouse is not over the tweet. Hint: You can use the register handlers for the hover event like this:

    <your selection>.hover(
        function () { //On mouse in },
        function () { //On mouse out }
    );
    Note The zebraOver class is already defined in the external CSS file, yamba.css.

Events

   Events Overview

   Binding An Event Handler

[Events Overview]


You can bind multiple events to the same handler by providing a space-separated set of event types, for example:

$('.header').on('click mouseleave', function () {
    $(this).css('background-color', 'yellow');
});

   Binding Shortcut Methods

blur

change

click

dblclick

error

focus

focusin

focusout

keydown

keypress

keyup

load

mousedown

mouseenter

mouseleave

mousemove

mouseout

mouseover

mouseup

resize

scroll

select

submit

unload

   Unbinding Handlers and “One-Shot” Handlers

Tip If you plan to unbind handlers, it’s best to do so by specifying the particular handler you want to unbind.

   The Event Object

Note If your handler function returns false, it has the same effect as invoking preventDefault() and stopPropagation() on the event.

   Event Delegation

   Event Delegation And JQuery

   .live() vs .delegate() vs .on()


As of jQuery 1.4, .live() can delegate to an element other than the document root. However, the syntax for doing so is cryptic.

   Events: Labs

For these labs, start with the file labs/yamba5.html. It includes a <script> element to load a file named events.js, which you should edit in the labs directory.

  1. Remember that during the lab on DOM manipulation, we saw that our new dynamically-added tweets were not removed when the user clicked on their little remove icon. Fix this problem with the new techniques you have just learned.

  2. Keep the status text area collapsed (define its height with jQuery to be 37px) and hide the "Tweet" button and counter (using the <your selection>.hide() method) until the user clicks on it for the first time. Set the text area height to be 56px and show the Tweet button and counter using the <your selection>.show() method.

  3. We have a character counter that displays 140 but currently it doesn’t update as we type our status. Implement this functionality into the character counter. (Hint: looking at this page might help: http://api.jquery.com/category/events/keyboard-events/)

  4. Modify the counter so that when the user has 10 or fewer characters remaining, it turns red. If the counter goes negative, disable the Tweet button.

  5. Change CSS width properties when the size of the browser window changes. Below are the conditions:

    • When the body width is less than 500px: min-width:300px for <div id="wrap"> and width:85% for <div id="content">
    • If the body width is larger than 500px: min-width:500px for <div id="wrap"> and width:66% for <div id="content">
  6. We already have hint text in the textarea, but it does not disappear when the user clicks on the textarea. Implement this hint functionality using the blur() and focusin() methods:

    • When the user gives focus to the text area, empty the default message or keep the message entered by the user.
    • When the text area does not have the focus anymore, check if the textarea is empty, and if so, display the hint.
  7. Change the background color of the tweets as the user hovers the mouse over them (just like we did in the CSS styling labs), except now you also want to support the same behavior for dynamically-added tweets.

Writing Your Own Plugins

The plugin pattern is a powerful mechanism for promoting good code organization and reuse. In this lesson we will learn to structure our code to create jquery plugins.

   Creating Your Own Plugin: Why?

   Creating Your Own Plugin: How?

   Adding configurability

It’s ok to accept arguments to the plugin function itself. If you have multiple arguments it is common practice to use an object and jQuery’s $.extend function to accept multiple configuration arguments but provide default values.

(function($){
    $.fn.pluginName = function(options) {
        var defaults = {'color': '#FF0000', 'length': 1000};
        var args = $.extend(defaults, options);
        //Implement your plugin here, using the args
    };
})(jQuery);

   Creating Your Own Plugin: Best Practices

Note With so many plugins out there, you should analyze the plugins you are considering using as if you were writing them with the previously mentioned best practices in mind.

   Plugins: Labs

For these labs, start with your previous completion of labs/yamba5.html. You finished the events lab with code in a file named plugins.js. Reorganize your code into plugins:

  1. Create a new filed called jquery.hint.js and create a plugin that encapsulates the "hint" functionality. Using the hint plugin should look like:

    $('mytextarea').hint();

    Be sure that your plugin would work for multiple controls on the same page!

  2. Create a new file called jquery.counter.js and create a counter plugin which counts the number of characters in a form input control and displays the number of remaining characters. The plugin should accept options to specify the max number of chars, the selector rule to display the count in, and the cutoff point at which the count color changes to red. It should also accept callbacks to be called when the number of characters remaining goes below or above 0. Using the plugin should look something like:

    $('mytextarea').counter({'max': 140, 'warning': 10, 'valid': show_button, 'invalid': hide_button, 'showin': '#counter'});

Effects and Custom Animations

In this chapter, we are going to discuss how to:

   JQuery Built-in Effects

   Showing or Hiding Elements

Note If you don’t provide a speed argument, the .show() and .hide() methods take effect immediately without an animation.

   Fading Effects

   Sliding Effects

   Creating Your Own Animations

$('.menu-li2').click(function(){
    $(this).animate({
       borderLeftWidth:"0px",
       borderRightWidth:"12px"
    }, 600);
});

Note CSS shortcut properties such as border: '1px solid black' are not supported. You would have to be more explicit:
$(selection).animate({
   borderWidth: "1px",
   borderStyle: "solid",
   borderColor: "black"
}, 600);

   Animation Notes

   Animation Queues

   Stopping Animations

   Additional Animation controls

   Effects and Custom Animations: Labs

For these labs, start with the file labs/yamba6.html. It includes a <script> element to load a file named effects_and_custom_animations.js, which you should edit in the labs directory.

  1. We want to slowly animate the whole page to move to the top when the user clicks on the "Go to top" button. Hint: use the scrollTop property on the <html> and <body> elements.

  2. When the user clicks on the "Hide" button, we want to hide the header and footer leaving only the content on the page

  3. Modify the "Hide" button from the previous lab so that it toggles between hide and show.

  4. Modify the previous example to make a slow toggle.

  5. When the user clicks on the "Tweet" button, we want to add this tweet to the top of the list of statuses. When the new status is added, slide it down slowly, fade it out fast, and then fade it in fast.

  6. Make tweets fade out when deleted and make sure that you handle dynamically-added tweets.

  7. Make the new status box slide down slowly when the user clicks on it for the first time.

  8. Make the side menu (<div id="sidemenu">) scroll when the user scrolls the page:

    • Listen for the scroll event on the window object.
    • Then animate the top property of the side menu.
  9. Create an accordion (without jQuery UI, which we will see later) using the side menu:

    • First, hide all the elements but the first element.
    • Remove the borders for the last <li> of each .menu_ul2.
    • When clicking on an .menu_li1, get its <ul> child.
    • Check if this same <ul> is hidden.
    • If this <ul> is hidden, find others that are visible and hide them.
    • Show the previously selected child.

Ajax

   What Is Ajax?

   Limitations Of Ajax

   Load HTML Content: The .load() Method

   Hijax With JQuery

   Select In Detail What To Load

   Advanced Loading Using The .load() Method

   JSON and JSONP

   Load JSON Data: The .getJSON() Method

   The Main Ajax Method: .ajax()

   Ajax Global Settings

   Error Handling

   Ajax: Labs

For these labs, start with the file labs/yamba7.html. It includes a <script> element to load a file named ajax.js, which you should edit in the labs directory.

Note ajax.js already implements some of the features we implemented in previous labs. Please do not remove them! It also provides a function, statusHTML(status), that constructs the HTML code for a tweet. You will call that method when looping through the JSON result object.
  1. Get the public timeline from yamba.marakana.com using JSONP:

    Note For the rest of the labs, you will be provided a virtual machine hosting an open source micro-blogging web application (statusnet). The page and the front-end script will have the same origin as the backend script so you will not have any cross-origin issues.
  2. Login and get the friends' timeline from the server using the $.ajax() method

    • URL to request: /api/statuses/friends_timeline.json
    • Data type: json
    • Username: student
    • Password: password
    • HTTP method: GET
  3. Post the new status to the server using the $.ajax() method

    • URL to request: /api/statuses/update.json
    • Data type: json
    • The status parameter contains the text to tweet
    • Username: student
    • Password: password
    • HTTP method: POST

Plugins

   Popular Plugins

   Easing Plugin

   Slideshow Plugins

   The ColorBox Plugin

   The Cycle Plugin

   Jcrop Plugin

   The Validation Plugin

   DataTable Plugin

   Plugins: Labs

For these labs, start with the file labs/yamba8.html. It includes a <script> element to load a file named plugins.js, which you should edit in the labs directory.

  1. Turn the list of tweets (<ol id="statuses">) into a sort of slideshow using the Cycle plugin.

  2. Use the Validation plugin on our registration form using the following rules:

    • All fields are required
    • Email address must be a valid address
    • Password must be at least 6 characters
    • Password confirmation must be equal to the password

jQuery UI

   What Is JQuery UI?

   Getting Started

   JQuery Widgets

   The Accordion Widget

   The Tabs Widget

   Dialogs

   JQuery UI Controls

   The Datepicker

   The Slider

   The Progress Bar

   Jquery UI Interactions

   Drag & Drop

   Drag & Drop: Example

Note The .draggable() method does not apply to elements that are created dynamically. You would need to use event delegation on the mouseenter event and then enable the draggable behavior on the clicked element

   Sortable elements

   Selectable Elements

   Resizable Elements

   jQuery UI animation

   jQuery UI: Labs

For these labs, start with the file labs/yamba9.html. It includes a <script> element to load a file named jquery_ui.js, which you should edit in the labs directory.

  1. Transform the side menu into an accordion using jQuery UI.

  2. Transform the <div id="tweets"> into tab navigation using jQuery UI.

  3. Improve the tab navigation so when you click on "Public timeline", public statuses will be dynamically loaded using the .getJSON() method.

    • URL to get public statuses: http://yamba.marakana.com/api/statuses/public_timeline.json?callback=?
    • Remember that you need to first catch which tab has been selected. For that supply a callback function to handle the select event as an init option like this:
      <your selection>.tabs({
         select: function(event, ui) {
           //Make your JSONP call and display result
         }
      });
  4. Display the <div id="dialog"> as a jQuery simple dialog when the page is ready.

  5. Display the <div id="confirm"> as a jQuery modal confirmation dialog when the user chooses to delete a tweet.

    • This modal dialog must have two buttons: "Yes" and "No"
    • If the user clicks on "Yes", close the dialog and remove the tweet (this is a simulation, do not make any AJAX calls) from the page using a fadeOut effect.
    • If the user clicks on "No", just close the dialog.
    • This dialog will have the title: "Delete Tweet".
    • This dialog must not be resizable.
  6. It would be nice to drag our tweets in to a "trash" area. When our tweets are dragged over the trash, we will fade them out and remove them from the DOM. Here are the requirements, using jQuery UI:

    • Our draggable elements will be all <li class="status"> elements:
      • Do not start dragging unless we have tried to drag the element on a distance of 20px.
      • When dragged, the opacity of our tweet has to be 0.7.
      • To make sure that the tweet will be displayed in the foreground, give it a high zIndex, like 1000.
      • When the tweet is dropped on an invalid place, make sure it is reverted to its original position.
    • Our droppable element will be the <div id="trash"> element.
      • This droppable can only accept our tweets and nothing else.
      • In terms of styling, the active class will be "ui-state-hover" and the hover class will be "ui-state-active".
      • We consider each draggable to be "over" a droppable when the mouse is over the droppable.

Advanced Concepts

   Best Practices: Loops

   Best Practices: Avoid Anonymous Functions

   Best Practices: Optimizing Selectors

   JQuery Utility Methods

   Avoiding Conflict With Other JavaScript Libraries

   Queuing And Dequeuing Animations

/

#