Jquery Tutorial : Jquery Ui

Forums » Bookshelf » Jquery Tutorial » Jquery Ui

9. jQuery UI

9.1. What Is jQuery UI?

  • jQuery UI is a library built on top of jQuery.
  • It provides advanced:

    • User-interface widgets (date picker, slider, progress bar, etc…)
    • Effects (color animation, shaking effect, explode effect, etc…)
    • Interactions (drag & drop, sorting, etc…)
  • jQuery UI is managed by and is part of the "jQuery Project" ⇒ http://jquery.org/

9.2. Getting Started

  • To start using jQuery UI, you need to download the library first.
  • From the jQuery UI homepage, you have many choices:

  • If you are using the Google hosted jQuery library, you need to download a theme (CSS file along with images) to apply on the components you are going to use soon.
  • From this page http://jqueryui.com/themeroller/, you can:

    • Create your own theme using the ThemeRoller
    • Choose an existing theme, ready to be used
  • Finally, you need to include the CSS and the library in the HTML file.

    <link href="jquery-ui-1.8.10.custom.css" type="text/css" rel="stylesheet"/>
    <script src="libs/jquery-ui-1.8.10.custom.min.js"></script>
    [Note]Note

    Do not forget to include the images folder included with the theme, this folder and the CSS should be contained in the same folder.

9.3. jQuery Widgets

  • jQuery UI provides you a lot of cool UI widgets that:

    • Enhance navigation (such as accordion and tabs)
    • Add some forms controls (such as autocomplete, special button, datepicker and slider)
    • Other controls (such as progress bar and dialogs)

9.4. The Accordion Widget

  • In your HTML page you might have a part representing a list of "headers" along with their related section of information.
  • The Accordion widget turns this part of the page into an accordion widget where only one section can been seen at a time:

    images/jquery_ui_accordion.png
  • Of course, you could implement your own accordion using the core jQuery library, however the Accordion widget gives you a lot of options, including:

    • Changing icons
    • Choosing event that trigger section opening
    • Settings sections height to the height of the biggest section or not
    • Etc…
  • This widget has some HTML semantics requirements.
  • The container that is being turned into an accordion must contain pairs of "headers" along with their sections like this:

    <div id="accordion">
        <h3><a href="#">First header</a></h3> 1
        <div>First content</div> 2
        <h3><a href="#">Second header</a></h3> 3
        <div>Second content</div> 4
    </div>

    1 2

    A "header" along with its section of information

    3 4

    Another "header" and information pair
  • As soon as you have the right markup, you are ready to apply the accordion to the main element containing header/section pairs (here in this example: <div id="accordion">):

    $('#accordion').accordion({ header:'h3' }); // 1

    1

    The accordion method takes an object as a parameter. This component is flexible and you can specify many options such as the header option that tells the accordion widget to consider <h3> elements as headers

9.5. The Tabs Widget

  • Tabs are used to separate the content in different sections while saving space on the page, and allows users to easily switch from one section of content to another.

    images/jquery_ui_tabs.png
  • Using specific semantics on the HTML side, you can easily turn parts of your page into tabs.
  • Let us take a look at this example:

    <div id="tabs">
        <ul> 1
            <li><a href="#tabs-1">First</a></li> 2
            <li><a href="#tabs-2">Second</a></li> 3
            <li><a href="#tabs-3">Third</a></li> 4
        </ul>
        <div id="tabs-1"> 5
          Lorem ipsum dolor....
        </div>
        <div id="tabs-2"> 6
          Phasellus mattis tincidunt...
        </div>
        <div id="tabs-3"> 7
          Nam dui erat...
          </div>
    </div>

    1

    This is the element containing the tabs

    2 3 4

    Each tab has an anchor to its corresponding element (the <div> in this example)

    5 6 7

    These elements represent the content for each tab
  • Now on the JavaScript side, you would just have to call the .tab() method on the element containing the tabs and content:

    $('#tabs').tabs();
  • There are a lot of options for this Tab widget that can be found at http://jqueryui.com/demos/tabs/#options

    • These options would be passed to the Tabs widget like this:

      $('#tabs').tabs({
        option1: 'value',
        option2: 'value'
      });
  • The following are the events that you can use to listen on the Tabs widget:

    • tabsselect, tabsload and tabsshow (fired in this exact same order)
    • tabsadd and tabsremove
    • tabsenable and tabsdisable

      [Note]Note

      Event listeners can directly be defined when creating the tab element. For instance for the tabsselect event:

      $('#tabs').tabs({
        select: function(event, ui) { ... } // 1
      });

      1

      The ui object contains several properties: ui.tab for the anchor element representing the clicked tab ui.panel representing the element containing the content of the selected tab ui.index representing the index of the clicked tab (zero based index)
  • Tabs can also load content dynamically using Ajax.

    • Tab links that have an href attribute with a relative URL to resources on the server will dynamically load the data in the content panel when clicked.

      [Note]Note

      Of course, do not forget about the same origin policy. In order to dynamically load content into your tabs, the page and the resources it is trying to access must be on the same server.

9.6. Dialogs

  • jQuery UI provides you with the ability to easily create dialogs (modal and non-modal dialogs).

    [Note]Note

    The difference between a modal and a non-modal dialog is that a modal dialog prevents the user from interacting with the rest of the page until it is closed.

  • A non-modal dialog looks like this in jQuery UI:

    images/jquery_ui_simple_dialog.png
  • A dialog is created from a <div> element having a title attribute representing the title of the window.

    <div id="dialog" title="Basic dialog">
        <p>Welcome on Yamba</p>
        <p>Yet Another Micro-blogging App</p>
    </div>
  • Next, using jQuery UI, we can quickly turn this <div> element into a basic non-modal dialog:

    $('#dialog').dialog(); // 1

    1

    The fastest way to create a new dialog. Of course, we can specify many options (such as height, width, if the dialog is modal or not, the position of the dialog, etc…) as a form of object ⇒ http://jqueryui.com/demos/dialog/#options
  • Another type of dialog that is often use is the modal dialog, which is used to get confirmation from the user before performing some action.
  • This example will show you how to create a modal confirmation dialog using the following HTML markup:

    $( "#confirm" ).dialog({
        title: "Delete Tweet", // 1
        resizable: false, // 2
        modal: true, // 3
        buttons: { // 4
            "Yes": function() {
                $(this).dialog("close"); // 5
                alert("You clicked on yes");
            },
            "No": function() {
                $(this).dialog("close");
                alert("You clicked on no");
            }
        }
    });

    1

    This is the title of the dialog

    2

    This states that the dialog cannot be resized

    3

    This states that the dialog is modal

    4

    This defines all of the buttons along with their text and handlers

    5

    This closes the dialog
  • This would produce the following result:

    images/jquery_ui_modal.png

9.7. jQuery UI Controls

  • jQuery UI comes with new controls that can be used in your form, such as:

    • The date picker
    • The slider
    • The progress bar
    • Etc…
  • The drawbacks of creating these controls yourself:

    • A lot of time required
    • Error prone

9.8. The Datepicker

  • The Datepicker is a component that allows you to display a calendar, allowing the user to choose a date.
  • The Datepicker:

    • Is tied to a standard form input field
    • Is opened when the user focuses on this same input (click or tab)
    • Returns the date to the input field as soon as the user chooses a date

      images/jquery_ui_datepicker.png
  • In the HTML code, create a normal input:

    <input type="text" id="datepicker">
  • Then on the JavaScript side using jQuery UI, you would do the following:

    $("#datepicker").datepicker();
  • This date picker is highly customizable. You can:

    • Format the date shown to the user in the input
    • Restrict the date range
    • Use different languages for your calendar
    • Directly embed the calendar on the page
    • Display month and year in a list
    • Display multiple months at a time
    • Etc…

9.9. The Slider

  • The jQuery UI .slider() method turns a <div> element into a slider:

    Figure 1. title

    images/jquery_ui_slider.png


  • On the HTML side, you would create an empty <div> element with an id like this:

    <div id="slider"></div>
  • On the JavaScript side, you would have to apply the .slider() method to the <div> like this:

    $( "#slider" ).slider();
  • There are of course a lot of options that you can configure here, such as having multiple handles and ranges, specifying the range, etc…

    [Note]Note

    Those handles can be moved with the mouse as well as with the direction key from the keyboard

  • There are also some events that you can use to listen. Event handlers receive two parameters:

9.10. The Progress Bar

  • The progress bar is a good visual way to show the state of completion for a process (percentage of completion):

    images/jquery_ui_progress.png
  • To create a progress bar, you need to first create the HTML structure like this:

    <div id="progressbar"></div>
  • Using jQuery UI and the .progressbar() method, you can quickly turn this structure into a jQuery UI widget:

    $("#progressbar").progressbar({
      value: 50
    });
  • Like any other widget, there are options and events that you can listen for. Details are available at http://jqueryui.com/demos/progressbar/

9.11. Jquery UI Interactions

  • jQuery UI also allows you to define "behaviors" on elements.
  • Using jQuery UI you can make your elements:

    • Draggable
    • Droppable
    • Resizable
    • Selectable
    • Sortable

9.12. Drag & Drop

  • Drag & drop allows you to make any element "draggable" on to other elements that are "droppable".
  • This is what you can do with a "draggable" element (An element that a user moves):

    • Constrain the movement (like dragging vertically or horizontally)
    • Delay the dragging movement depending on the dragging distance or time in order to avoid accidental dragging
    • Fine-grained snapping of the dragged element
    • Possibility to revert the dragging movement on a certain condition (if not dropped at the right place for instance)
    • Provide a visual helper to the user when dragging an element
    • Position the mouse where you want in the dragged element
  • This is what you can do with a "droppable" element (an element that "receives" the "draggable" element):

    • Choose accepted elements
    • Provide feedback when the user drags and/or drops and element on the "droppable" location
  • You can also listen for events:

9.13. Drag & Drop: Example

  • Let us see an example on how to do drag & drop using jQuery UI:
  • This will be our HTML:

    <div class="draggable"> 1
      <p>An element to drag on the page</p>
    </div>
    
    <div class="draggable"> 2
      <p>An element to drag on the page</p>
    </div>
    
    <div id="droppable"> 3
      <p>Drop element here</p>
    </div>

    1 2

    These elements are the one that will be dragged on the page

    3

    This element will be the one that will be receiving the draggable element. This is the droppable element
  • Time to add draggable and droppable interactions to these elements:

    $('.draggable').draggable({ // 1
        distance:20, // 2
        opacity:0.7, // 3
        zIndex:1000, // 4
        revert:'invalid' // 5
    });
    
    //Make the trash being droppable
    $('#droppable').droppable({ // 6
        accept:'.draggable', // 7
        activeClass:'ui-state-hover', // 8
        hoverClass:'ui-state-active', // 9
        tolerance:'pointer', // 10
        drop: function(event,ui) { // (11)
            var $element = ui.draggable; // (12)
            $element.fadeOut('slow',function() {
                $(this).remove();
            });
        }
    });

    1

    This will turn your elements with the class draggable into draggable elements

    2

    distance specifies the distance in pixels that the user has to move before the drag starts

    3

    opacity sets the opacity of the dragged element

    4

    zIndex brings the element to the foreground or the background of the page depending on its value

    5

    revert allows you to choose if you want to revert the dragged element to its initial position when dragging stops on a valid position or not

    6

    This will turn your element with the id droppable into a droppable element

    7 8

    activeClass sets the class to use for the droppable when a user starts to drag an element

    9

    hoverClass sets the class to use for the droppable element when a user drags an element over the droppable element

    10

    tolerance allows you to specify what mode is used to determine whether or not a draggable is "over" a droppable.

    (11)

    drop allows you to specify the function to call when a draggable has been dropped over a droppable

    (12)

    ui.draggable refers to the draggable element
[Note]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

9.14. Sortable elements

  • jQuery enables you to make your elements sortable using the sortable method.
  • Take for example, an HTML list like this one:

    <ul id="sortable">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
    </ul>
  • Next, to make the list items sortable, you would have to use the .sortable() method:

    $('#sortable').sortable(); // 1

    1

    Of course this method can take several options passed as a JavaScript object. Those options are available here ⇒ http://jqueryui.com/demos/sortable/#options. Sortable items also share draggable properties

9.15. Selectable Elements

  • Using jQuery UI, you can enable an element or a group of elements to be selectable.

    • You can click on them to select them
    • Ctrl/meta key plus click and/or drag also works for selectable
  • Imagine an HTML list like this one:

    <ul id="selectable">
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
    </ul>
  • Then to make the list items selectable, you would have to use the .selectable() method:

    $('#selectable').selectable(); // 1

    1

    Of course this method can take several options passed as a JavaScript object. Those options are available here ⇒ http://jqueryui.com/demos/selectable/#options

9.16. Resizable Elements

  • jQuery provides you the ability to resize any DOM element by calling the .resizable() method on this element. Of course, you can specify more options:

    • Preserve the aspect ratio
    • Set the minimum/maximum width and height
    • Provide visual feedback using a transparent ghost of the element being resized
    • Synchronize resizing between elements
    • Animate the element on resizing etc…
  • There are also events that you can listen for, such as create, start, resize and stop
  • Let us take the following HTML structure as an example:

    <div id="resizable">
      <!-- Content of the div -->
    </div>
  • Using jQuery, you can make this element to be resizable:

    $(#resizable).resizable(); // 1

    1

    This makes the element resizable. For more options and events ⇒ http://jqueryui.com/demos/resizable

9.17. jQuery UI animation

  • jQuery UI adds a lot more functionality for animations. It adds:

  • jQuery UI also extends existing methods such as:

    • The .animate() method to support color animation when animating the following properties: backgroundColor, borderBottomColor, borderLeftColor, borderRightColor, borderTopColor, color and outlineColor
    • The .addClass(), .removeClass() and .toggleClass() methods now support class animation by adding a second parameter (the time of the animation)
    • The .toggle(), .show() and .hide() methods have been enhanced to accept the jQuery UI advanced effects