jQuery UI – Part 4 Draggable & Droppables

Posted by mdrisser on 2008/08/09 under Development, JavaScript, Misc., UI, Web Browsers, jQuery | 5 Comments to Read

Now that we’ve looked at the core components of the jQuery UI, we’ll start taking a look at the other parts of the UI. In addition to the components the UI also contains some actions and effects.

The actions are draggables, droppables, sortables, selectables and resizeables. We’re not going to worry about effects just yet, in this post we’ll concentrate on draggables and droppables.

To get started, let’s create a simple page, just as we’ve been doing. We want to add an element that will be draggable, this can be any element on the page. For our example we’ll create a div and give it a little styling to make it a touch easier to work with.


Now if you load the page you should have a 64px square, gray box with a light gray border. Now we need to make our box draggable. Add the following code to the head of your page:





Remember to change the script src attribute to match the location for your scripts.

Now if you click and drag on your gray box, it should move to wherever you want it to. Pretty simple, huh? But of course we’re not finished yet, there are options to draggable that we need to take a look at.

The first one we’ll see is ‘axis’. The ‘axis’ option allows us to specify that the draggable is draggable in only 2 directions, either vertically (’axis’: ‘y’) or horizontally (’axis’: ‘x’). Let’s go ahead and set our draggable to only move horizontally:

$('#dragMe').draggable({
    'axis': 'x'
});

Reload your page and try it out. You can’t move your box up and down can you? Just for fun, set ‘axis’: ‘y’, reload your page and try it out.

If you’re done playing we’ll move on :)

One of the other options we’ll look at is the ‘containment’ option. Basically what this does is limit the area in which you can drag the box. You can set this to be a parent element, the document window, or a jQuery selector.

Let’s wrap our box in another div and set it to a 200px square with a black border.

Replace the ‘axis’: ‘y’ option with ‘containment’: ‘#boxParent’.

Now, reload your page and try it out. You should have only been able to drag the box within the bounds of the parent div.

The last option we’ll look at for draggables is the ‘revert’ option. I’m not going to tell you what it does, I’ll show you how to implement it and then let you discover it for yourself :)

$('#dragMe').draggable({
    'revert': true
});

Drag the box somewhere and let go of it.

It should have snapped right back to its starting point.

There are quite a few other options that I’ll let you look at on your own, refer to the UI docs to see what they are and what their arguments are.

Let’s look at an action that ties right in with draggables, and that is droppables. Droppables really function as targets for draggables.

Create another div to be the droppable: