سؤال

I have a draggable div that I want to be able to drag and drop into a droppable div.

Once dropped, it should no longer be draggable and it should be positioned at the center of the droppable div.

I got that working, but I now want to add an AJAX request when the div is dropped. If the AJAX call is successful then the draggable div should no longer be draggable and be positioned at the center of the droppable div.

With my current code, when I add the AJAX call, everything works ok and then the droppable div gets put back to where it started. Does anyone know how I can stop this happening?

I have a demo of the problem here

The code is as follows:

HTML

<div id="playingArea" class="droppable">Drop in here</div>

<div id="player" class="draggable">Drag Me</div>

CSS

#playingArea{
    border:1px solid black;
    min-height: 150px;
    min-width: 150px;
    margin-bottom: 30px;
}

#player{
    border:1px solid red;
    height: 50px;
    width: 50px;
}

Javascript

$(function() {
    $('.draggable').draggable({
        containment : 'document',
        cursor : 'move',
        revert : true
    });

    $('.droppable').droppable({
        accept : '.draggable',
        hoverClass : 'hovered',
        drop : handleDrop
    });
})

function handleDrop(event, ui) {
    $.ajax({
        url : "/echo/json/",
        dataType : 'json',
        error : function(data, errorThrown) {
            alert('request failed :' + errorThrown);
        },
        success : function(data) {
            positionBox(event, ui);
        }
    });
}

function positionBox(event, ui) {
    ui.draggable.draggable('disable');
    ui.draggable.position({
        of : $("#playingArea"),
        my : 'center',
        at : 'center'
    });
    ui.draggable.draggable('option', 'revert', false);
    $("#player").css({
        opacity : 1
    })
    alert("looks ok now - but it won't stay here");
}
هل كانت مفيدة؟

المحلول 2

I got it sorted in the end, just had to set the revert to "invalid" rather than true:

$('.draggable').draggable({
    containment : 'document',
    cursor : 'move',
    revert : "invalid"
});

and then remove the revert option in the positionBox function. I've updated the fiddle to reflect the solution for future reference.

نصائح أخرى

You have to set the attribute revert to false

$('.draggable').draggable({
    containment : 'document',
    cursor : 'move',
    revert : false
});
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top