javascriptjqueryhtmlcssjquery-ui

Dropping a draggable in a droppable at the drop position


I have been trying to clone and drop a draggable at the position in a droppable at the coordinates where the drop happens. I have found examples online that deal with appending draggables to droppables, but they all seem to move the draggable to a specific part of the droppable on the initial drop.

Here is an example that does just that: - http://jsfiddle.net/scaillerie/njYqA/

//JavaScript from the jsfiddle
jQuery(function() {
jQuery(".component").draggable({
    //  use a helper-clone that is append to 'body' so is not 'contained' by a pane
    helper: function() {
        return jQuery(this).clone().appendTo('body').css({
            'zIndex': 5
        });
    },
    cursor: 'move',
    containment: "document"
});

jQuery('.ui-layout-center').droppable({
    activeClass: 'ui-state-hover',
    accept: '.component',
    drop: function(event, ui) {
        if (!ui.draggable.hasClass("dropped"))
            jQuery(this).append(jQuery(ui.draggable).clone().addClass("dropped").draggable());
        }
    });
});

Is there anyway I can make the draggable stay at the coordinates where the drop occured?


Solution

  • you must define the coordinates in the cloned element on the drop:

       drop: function(event, ui) {
            if (!ui.draggable.hasClass("dropped")){
       
                var clone=jQuery(ui.draggable).clone().addClass("dropped").draggable();
                clone.css('left',ui.position.left);    
                clone.css('top',ui.position.top);
            
                jQuery(this).append(clone);
            }
        });
    

    and also set the position absolute by css on the cloned components

    .ui-layout-center .component {
       position:absolute !important;   
    }
    

    Here is working: http://jsfiddle.net/o2epq7p2/