Examples of Using Drag Functionality

In this section, we’ll try out some of the drag functionality discussed in this chapter.

Carrying Out a Treatment When Moving

Let’s display the coordinates of an element as it is being moved (Figure 10-1):

<script src = jquery.js></script>
<script src = jqueryui/js/jquery-ui-1.8.16.custom.min.js></script>

<link rel=stylesheet type=text/css
      href=jqueryui/css/smoothness/jquery-ui-1.8.16.custom.css />

<div id=div1 style="border:solid 1px;background-color:gainsboro;">
  <span>Item 1 to move</span><br /><br />
  <span>Item 2 to move</span><br /><br />
  <span>Item 3 to move</span>

<p>Start : <span id=start></span></p>
<p>Drag : <span id=drag></span></p>
<p>Stop : <span id=stop></span></p>


$("#div1 span").draggable ({
  start : function (event, ui)
    $("#start").text (ui.offset.top + ", " + ui.offset.left);
  drag : function (event, ui)
    $("#drag").text (ui.offset.top + ", " + ui.offset.left);
  stop : function (event, ui)
    $("#stop").text (ui.offset.top + ", " + ui.offset.left);


The first displacement causes the start, while the movements that follow are managed by the drag event. When the mouse is released, the stop event is triggered.

Coordinates of the drag

Figure 10-1. Coordinates of the drag

Imposing Limits on Displacement

You can limit the movement of elements on the screen. Here, we’ll look at the various possible constraints.

Constraining the displacement ...

Get jQuery UI now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.