Pergunta

I have been experimenting with this code: jsfiddle It highlights and let you know which boxes you can drop the boxes onto but it is not accepting any droppables. Does anyone know how I can alter this code to accept a droppable instead of it just reverting back?

$(".DragItem").draggable({
    revert: true,
    helper: "clone" 
});

$(".DropItem").droppable({
    tolerance: "touch",
    over: function (event, ui) {
        var dropItem = $(this);
        var dragItem = $(ui.draggable);
        var valid = String(dropItem.data("id")).indexOf(dragItem.data("id")) > -1;
        if (valid) {
            dropItem.addClass("DropTargetValid");
        } else {
            dropItem.addClass("DropTargetInvalid");
        }
    },
    out: function (event, ui) {
        var dropItem = $(this);
        dropItem.removeClass("DropTargetValid");
        dropItem.removeClass("DropTargetInvalid");
    },
    deactivate: function (event, ui) {
        var dropItem = $(this);
        dropItem.removeClass("DropTargetValid");
        dropItem.removeClass("DropTargetInvalid");
    } 
});
Foi útil?

Solução

You will need to append the clones() to the correct divs and revert them if they don't match, first accept: all the dragable elements and then handle the revert in the drop: section. also you will need to create and save the origin position for the ellement you clone and drag so you can revert him to its original position and then removing it from the page.

Here is the finall script demo:

JSnippet demo draggable & droppable

have fun!

Outras dicas

I would start from something like this:

  • re-use the built-in query-ui functionality, e.g. "accept" or "activeClass" parameters of a droppable
  • if there is a small number of containers - you might declare "droppables" separately and use "accept" to e.g. allow only certain classes of draggables (like in the demo below)
  • trying to "hack" draggables & droppables is possible but not very easy, especially with complex elements (if draggables and droppables have more complex html structure than just flat divs)

Sample:

$(".drop1").droppable({
    accept: '.drag1',
    activeClass: 'DropTargetValid',
    drop: function (ev, ui) {
        $(ev.target).append(ui.draggable.clone());
    }
});

Fiddle demo

--- EDIT ---

Updated demo

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top