Wednesday, July 2, 2014

Containing Draggables by Parent and Grid

The draggable widget, available in jQuery UI, doesn't constrain movement by default. If you create a draggable, without passing in any options, you're free to drag it around anywhere on the page. While this makes sense as out-of-the-box default behaviour, it's very limited in terms of practicality. In the real world, you would probably want to specify a droppable target. Or, at least constrain the movement to within a specific element on your page.

Let's say that I have a small container div, inside, a div that can be moved around. But not in any direction, only horizontally. This can be controlled by the axis option. However, that's usually not enough. Giving the draggable an axis, doesn't tell it that it can't move outside the parent element. For that, you would use the containment option, and specify "parent".

To further refine how our draggable is allowed to move, within the parent, we could pass it a grid value. This makes the draggable element "snap" into it's position. Here's an example that shows how to snap the draggable into it's potential horizontal position.

$( '.container div' ).draggable({
    containment: 'parent',
    grid: [ 40, 0 ]
});