views:

20

answers:

1

how can i make the containment to be a subset of cells. ie leaving out the header row and the leftmost column?

+1  A: 

The optimal would be to just send in a selector for the fields that should consitute the containment, but since that won't work I fiddled with an alternative solution. I wouldn't say it's very optimal but I'll give it a go.

Find the extreme points (left, top, right, bottom) of the cells that you are supposed to drag the draggable withing and set these points as the containment of the draggable. In my example I've given these elements (the tds of the table) the class containmentTD. It doesn't take into account borders, padding ect so it'll need to be tweaked if that's important.

//The TD elements that are to be included when
//we find the dimentions of the containment
var td_elements = $(".containmentTD");

//This will hold the extreme points of the containment
var points = {
    left: td_elements.eq(0).position().left,
    top: td_elements.eq(0).position().top,
    right: 0,
    bottom: 0
};

//Find the points of the containment
td_elements.each(function() {
    var t = $(this);
    var p = t.position();
    var width = t.width();
    var height = t.height();

    points.left = Math.min(p.left, points.left);
    points.top  = Math.min(p.top , points.top );
    points.right = Math.max( points.right, p.left + width);
    points.bottom = Math.max( points.bottom, p.top + height);
});

//This will only work "perfectly" when all draggables have
//the same dimentions
points.bottom -= $("div.draggable:first").height();
points.right  -= $("div.draggable:first").width();

$("div.draggable").draggable({
    containment: [points.left, points.top, points.right, points.bottom]
});

Here's a demo: http://jsfiddle.net/uTyTY/ Note that the red square is only there to visualize the containment area

Simen Echholt