Search code examples
jquery-ui-draggablejquery-ui-droppablereplacewith

jQuery drag and drop replace element and dynamically create droppable


I have draggable elements that can be dropped into a container. Within the container is a target 'p' for the user to drop the element on. When dropped, the element replaces the target and dynamically creates a new target. This works great the first time, but subsequent drops don't seem to replace the dynamically created target. Code below and jsfiddle. Any help would be greatly appreciated cos i feel like I'm close but just missing something.

html

<div class="dragMe" data-value="one">Drag me!</div>
<div class="dragMe" id="two">Drag me!</div>
<div class="dragMe" id="three">Drag me!</div>
<div id="container"><p class="replaceText">Drag here</p></div>

css

#container {
border: solid black 1px;
height: 100px;
width: 100%;
display: flex;
flex-flow: row nowrap;
}

.replaceText {
    height: 96px;
    width: 96px;
    background-color: orange;
    margin: 1px;
    border: 1px solid blue;
}

.dragMe {
    color: white;
    background-color: #BADA55;
    width: 98px;
    margin: 2px;    
}

jQuery

$('.dragMe').draggable({
    helper: 'clone',
    cursor: 'move',
});

$('#container').droppable({
   accept: '.dragMe',
   drop: handleDropEvent
});
function handleDropEvent (event, ui) {
    var draggable = ui.draggable;
    var newtarget = '<p class="replaceText">Drag here</p>';

    $('.replaceText').replaceWith(draggable);
    $('#container .dragMe').after(newtarget);
}

Solution

  • You should replace

    $('#container .dragMe').after(newtarget);

    with

    $('#container .dragMe').last().after(newtarget);

    jsfiddle project here