How about this:
$(function() { $(".draggable").draggable(); $(".item").droppable({ drop: function(event, ui) { var $this = $(this); $this.append(ui.draggable); var width = $this.width(); var height = $this.height(); var cntrLeft = width / 2 - ui.draggable.width() / 2; var cntrTop = height / 2 - ui.draggable.height() / 2; ui.draggable.css({ left: cntrLeft + "px", top: cntrTop + "px" }); } }); });
Edit: I noticed that you have text in the target div . If you want this to work with other elements in droppable, you can place the moved element absolutely and offset it with the left and top parent:
var width = $this.width(); var height = $this.height(); var top = $this.offset().top; var left = $this.offset().left; var cntrLeft = (width / 2 - ui.draggable.width() / 2) + left; var cntrTop = (height / 2 - ui.draggable.height() / 2) + top;
and
ui.draggable.css({ left: cntrLeft + "px", top: cntrTop + "px", zIndex:1, position: 'absolute' });
Notes:
ui.draggable is a draggable item that has been reset to droppable.$this.append(ui.draggable) adds a dragged item to the droppable div , so positioning can be done exactly.
See a live example here: http://jsfiddle.net/andrewwhitaker/F3sD3/
Andrew Whitaker
source share