Search code examples
jquery-uidraggable

jQuery draggable Snap to Center while dragging


I have draggable object in the page, and it has snap setting for the region.

<div class="drag-bound">
  <div id="obj"></div>
</div>

$('#obj').draggable({
  snap: ".drag-bound",
  snapTolerance: 5
})

So now if $('#obj') is dragged near the border of ".drag-bound", it gets snapped there.

The problem is I want $('#obj') is snapped to the center of the ".drag-bound", too.

Is there any good idea how to make it happen?

Should I make custom code inside of drag event handler?

Is there any good and easy option inside of it?


Solution

  • Alright, so far from my investigation, there seems not to be a good option to accomplish my purpose.

    I have made custom code inside of drag event handler like following:

           fn.branding.$resizable.draggable({
    
              snap: ".resize-bound",
              snapTolerance: 5,
    
              drag: function(event, ui) {
    
                var ui_w = ui.helper.width();
                var ui_h = ui.helper.height();
                var margin = $(this).draggable("option", "snapTolerance");
    
                /////////////////////////////////////////////////////////
                // do custom snapping here
                //
                if (!(Math.abs((ui.position.left + (ui_w)/2) - (fn.branding.modal_preview_width/2)) > 2 * margin)) {
                  ui.position.left = Math.round((fn.branding.modal_preview_width - ui_w)/2);
                }
    
                if (!(Math.abs((ui.position.top + (ui_h)/2) - (fn.branding.modal_preview_height/2)) > 2 * margin)) {
                  ui.position.top = Math.round((fn.branding.modal_preview_height - ui_h)/2);
                }
    
              });