Plastic
Plastic

Reputation: 10318

JQuery UI Drag & Drop without dropping

I'm new to jQuery UI and I don't really need to drop anything but a specific data attribute from the dragged element. With that data I will build a new element inside the drop element.

My html looks like:

<div class="dropElem">
    <div class="cod">Empty</div>
    ..elements i will populate later..
</div>

<div class="dragElem" data-cod='cod1'>
    <div>Data</div>
    ...
</div>
<div class="dragElem" data-cod='cod2'>
    <div>Data</div>
    ...
</div>

and my Javascript is like this:

$('.dragElem').draggable({
    helper: "clone",
    revert: "true",
    cursorAt: {top: 0, left: 0},//mandatory for my css structure
    start: function (event, ui) {
        var clone = $(ui.helper);
        clone.addClass('helper')//class added to style the helper
    }
});

$('.dropElem').droppable({
    activeClass: "activeDrop",
    hoverClass: "hoverActiveDrop",
    tolerance: "pointer",//mandatory for my css structure
    drop: function (event, ui) {
        var cod = ui.helper.data('cod'));
        //make new elements based on data received
     }
 });

Basically I use helper's dragging visual effect to transport data from one element to another.

What I need to do after drop is to disable the dragged element from being dragged again (I will add a class to highlight this) and to disable the droppped-in elemen from receiving any other dragElem (I will add a class to it too).

PS: I'm also not sure if var cod = ui.helper.data('cod')); is the best way to grab the data-attribute.

Any suggetion will be appreciated!

Upvotes: 1

Views: 926

Answers (1)

T J
T J

Reputation: 43156

You can specify a class in the cancel option and add that particular class to the draggable inside the drop callback to prevent further dragging. For disabling the droppable, you can use the disable method:

$('.dragElem').draggable({
  helper: "clone",
  revert: "true",
  cancel: ".disable"
});

$('.dropElem').droppable({
  drop: function(event, ui) {
    var cod = ui.draggable.addClass("ui-state-disabled").data('cod');
    console.log(cod);
    $(this).droppable("disable");
  }
});
.dragElem {
  width: 50px;
  height: 50px;
  margin: 10px 5px;
  background: hotpink;
}
.dropElem {
  width: 150px;
  height: 50px;
  background: dodgerblue;
}
<link href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div class="dropElem"></div>
<div class="dragElem" data-cod='cod1'>
  <div>1</div>
</div>
<div class="dragElem" data-cod='cod2'>
  <div>2</div>
</div>

Upvotes: 1

Related Questions