Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a JQuery Draggable with a smaller clone?

I have a large element that is displayed on the screen that I would like to be able to drop on a smaller drop target. Therefore, I want to decrease the size of the draggable clone to match the size of the drop target. I thought it would look nice to animate this. I can't seem to get the smaller clone to center around the cursor while dragging though. Any ideas? Here is a what I tried: http://jsfiddle.net/a3Cj2/

$( ".draggable" ).draggable({
    helper: 'clone',
    start : function(event, ui){
        ui.helper.animate({
            width: 80,
            height: 50
        });
    }, 
    drag : function(event, ui){
        ui.helper.offset({
             left: event.pageX,
             top: event.pageY
        });
    }
});

$("#target").droppable({
    drop : function(event, ui) {
       console.log('dropped');     
    }
});
like image 781
Jon Hargett Avatar asked Apr 29 '13 21:04

Jon Hargett


2 Answers

Simplest approach by far is to use the cursorAt option with 'left' and 'top' set to half the dimensions of the shrunken helper.

$(".draggable").draggable({
    helper: 'clone',
    start: function (e, ui) {
        ui.helper.animate({
            width: 80,
            height: 50
        });
    },
    cursorAt: {left:40, top:25}
});

Updated fiddle

like image 104
Beetroot-Beetroot Avatar answered Oct 02 '22 15:10

Beetroot-Beetroot


Wow, that took more work than I thought! Here's the fix:

$( ".draggable" ).draggable({
    helper: 'clone',
    start : function(event, ui){
        ui.helper.animate({
            width: 80,
            height: 50,
            marginLeft: (300-80)/2 - (300/2 - event.offsetX),
            marginTop: (200-50)/2 - (200/2 - event.offsetY)
        });
    }, 
    drag : function(event, ui){

    }
});

$("#target").droppable({
    drop : function(event, ui) {
       console.log('dropped');     
    }
});

You need to account for the event position and center it according to the difference between the centers of both sized draggables.

See fiddle here.

like image 45
Mike Marcacci Avatar answered Oct 02 '22 17:10

Mike Marcacci