Search code examples
jqueryjquery-uijquery-ui-droppable

Restore drag and drope positions


I use drag and drope jquery ui in my code. And the code works fine. But user should have some ability to edit data after saving. It means that I need to restore drag and drope positions when user opens the page again. I try to use trigger but I can't emulate "drop ui" How can I do it?

$( ".draggable-children-username" ).draggable({
    snap: ".draggable-in-box",
    opacity: 0.7,
    revert: 'invalid',
    helper: "clone"
});
$(".draggable-in-box").droppable({
    accept: $(".draggable-children-username"),
    hoverClass: "dropHover",
    drop: function (ev, ui) {
        $(this).trigger("DopeEvent", ui);
    }
});

$( ".draggable-in-box" ).bind("DopeEvent", function(event, ui ){
    console.log(ui);

    var me = ui.draggable.clone()
    ui.draggable.draggable("disable")
    me.appendTo(this)
    .addClass("newClass");
    me.draggable({
        accept: ".draggable-in-box",
        revert: function(valid) {
            if(!valid) {
                this.remove();
                $(".dr-children-id-"+this.attr("data-id")).draggable("enable");
            }
        }
    });
});

$( ".draggable-in-box" ).trigger("DopeEvent", $( ".dr-children-id-140" ));

Current error: Uncaught TypeError: ui.draggable.clone is not a function

http://jsfiddle.net/vjGY4/123/


Solution

  • A few fixes. Working example of what I think you're trying to do:

    http://jsfiddle.net/Twisty/vjGY4/125/

    JQuery

    $(".draggable-children-username").draggable({
      snap: ".draggable-in-box",
      opacity: 0.7,
      revert: 'invalid',
      helper: "clone"
    });
    
    $(".draggable-in-box").droppable({
      accept: $(".draggable-children-username"),
      hoverClass: "dropHover",
      drop: function(ev, ui) {
        $(this).trigger("DopeEvent", ui.draggable);
      }
    });
    
    $(".draggable-in-box").bind("DopeEvent", function(event, ui) {
      console.log(ui);
    
      var me = $(ui).clone();
      //ui.draggable.draggable("disable")
      me.appendTo(this)
        .addClass("newClass");
      me.draggable({
        accept: ".draggable-in-box",
        revert: function(valid) {
          if (!valid) {
            this.remove();
            $(".dr-children-id-" + this.attr("data-id")).draggable("enable");
          }
        }
      });
    });
    
    $(".draggable-in-box").trigger("DopeEvent", $(".dr-children-id-140"));
    
    1. Do not assume you're being passed a draggable object or a jquery object in you DopeEvent. Use var me = $(ui).clone();
    2. In your drop, you need to pass the element like so: $(this).trigger("DopeEvent", ui.draggable);

    Hope that helps. You could improve your event by checking what is being passed. Something like if(typeof ui === "object"){} could work.