Skip to content Skip to sidebar Skip to footer

Drag And Drop Issue Jquery

I have the code below using the script i am making stuff draggable and droppable. currently i have two pieces for draggable content, and two place they can be dropped if correct th

Solution 1:

You will need to avoid using HTML id for this and start using classes. Here is how to do that, with a working example:

Your HTML:

<divid="draggable_2"class="ui-widget-content draggable-item"><p>draggable_2</p></div><divid="draggable"class="ui-widget-content draggable-item"><p>draggable</p></div><divclass="ui-widget-header droppable-item"data-accept="#draggable"><p></p></div><divclass="ui-widget-header droppable-item"data-accept="#draggable_2"><p></p></div><divclass="ui-widget-header droppable-item"data-accept="#draggable_3"><p></p></div>

Your javascript:

$(function () {
    $(".draggable-item").draggable();

    $('.droppable-item').each(function (i, ele) {
        // Gets the accepted from the HTML property "data-accept"var accept = $(this).data('accept');

        // This is just to show what the item accepts. you can remove it.
        $(this).find('p').text('accepts: ' + accept);

        // Init the jQuery UI droppable()
        $(this).droppable({
            accept: accept,
            drop: function (event, ui) {
                $(this)
                    .removeClass("ui-widget-header")
                    .addClass("ui-state-highlight")
                    .find("p")
                    .html("Dropped!");
            },
            out: function (event, ui) {
                $(this).removeClass("ui-state-highlight").addClass("ui-widget-header")
                    .find("p")
                .html("accept: " + accept);
            }
        });
    });
});

Solution 2:

If I understand your question correctly, you want every draggable to be droppable only its droppable and no other droppable div.

You've already achieved this by adding the accept: "#draggable" in your code for every droppable.

You can add this extra line of code so that if your draggable is dropped anywhere other than its droppable, it will go back to its droppable. $( "#draggable, #draggable2" ).draggable({ revert: "invalid" });

This code can be shortened if you added the same class (like class=draggables to every draggable html element and then you can juse use $( ".draggables" ).draggable({ revert: "invalid" }); to mark them all.

Here is a jsfiddle to show the example.

Post a Comment for "Drag And Drop Issue Jquery"