jQuery UI how to set draggable containment option on parent's parent

steampowered picture steampowered · Nov 10, 2011 · Viewed 37.6k times · Source

The jQuery UI Draggable interaction has a nice property for setting the containment as the parent.

$( ".selector" ).draggable({ containment: 'parent' });

I wish to set the containment as the parent's parent. There is no string value to accomplish this, as string the options are

'parent', 'document', 'window', [x1, y1, x2, y2]

I could calculate x1,y1,x2,y2 of the parent's parent at page load and use those values to set boundaries for a container relative to the document. But the container position can change relative to the parent's parent position if the window is resized after page load. The native 'parent' option keeps the draggable element within the parent element regardless of window resizing.

Is there a way to accomplish this draggable containment using the parent's parent? .

Answer

rossipedia picture rossipedia · Nov 10, 2011

As per the documentation, the containment option can also be a jquery selector or an actual element. So you can do this:

$('.selector').draggable({
    containment: $('.selector').parent().parent()
});

Or even better yet:

$('.selector').each(function(){
    $(this).draggable({
        containment: $(this).parent().parent()
    });
});