jQuery UI sortable tolerance option not working as expected

istvan.halmen picture istvan.halmen · May 17, 2012 · Viewed 8.5k times · Source

Here is the part from jQuery UI documentation for the tolerance option:

This is the way the reordering behaves during drag. Possible values: 'intersect', 'pointer'. In some setups, 'pointer' is more natural.

intersect: draggable overlaps the droppable at least 50%

The default is intersect, but if the mouse pointer is not above the sortable items, the sort does not happen, no matter that the dragged element is at least 50% over another sortable item (the functionality I expect) This happens on the demo page as well (linked above)

Is this a bug in jQuery UI, or am I understanding it wrong?

Answer

istvan.halmen picture istvan.halmen · May 22, 2012

For those with the same problem here's the workaround I use:

$('#sortable').sortable({
    axis: 'x',
    sort: function (event, ui) {
        var that = $(this),
            w = ui.helper.outerWidth();
        that.children().each(function () {
            if ($(this).hasClass('ui-sortable-helper') || $(this).hasClass('ui-sortable-placeholder')) 
                return true;
            // If overlap is more than half of the dragged item
            var dist = Math.abs(ui.position.left - $(this).position().left),
                before = ui.position.left > $(this).position().left;
            if ((w - dist) > (w / 2) && (dist < w)) {
                if (before)
                    $('.ui-sortable-placeholder', that).insertBefore($(this));
                else
                    $('.ui-sortable-placeholder', that).insertAfter($(this));
                return false;
            }
        });
    },
});​

This works for a horizontal sortable, for a vertical one change outerWidth to outerHeight and position.left to position.top everywhere.

Here's a complete working example