javascriptjquerydrag-and-dropdraggablejquery-ui-selectable

Drag non-selectee div within jquery selectable


I'm trying to make a jquery selectable that makes some elements selectable using filter, but also have some other elements with a different class be available for dragging (but I am not trying to make the same elements selectable and draggable).

Here is a basic example: the goal is to be able to drag the first 'x' (which is a div with class .boundary) into the second 'x' and get some feedback, while the divs A, B, C (with class .tok) are normally selectable. These two things should not interact with each other: A B and C should be selectable, and each 'x' should be draggable.

enter image description here

I don't need the 'x' divs to be fully mobile, or even change position at all, just to drag from one into the other, maybe see each x I pass highlighted in some way, and get the information which x was dragged into which when I drop.

#selectable .ui-selecting {
  background: #FECA40;
}

#selectable .ui-selected {
  background: #F39814;
  color: white;
}

.tok {
  display: inline-block;
  margin: 1px
}

.boundary {
  display: inline-block;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script>
  $(function() {
    $("#selectable").selectable({
      filter: '.tok'
    });
  });

  // Option 1: with jquery draggable
  $(".boundary").draggable();

  // Option 2: bind dragstart etc.
  $(document).ready(function() {
    $('.boundary').on("dragstart", function(event) {
      alert('drag started');
    });
    $('.boundary').on("dragenter dragover drop", function(event) {
      event.preventDefault();
      alert(event.type);
    });
  })
</script>

<div id="selectable">
  <div id="t1" class="tok">A</div>
  <div id="b1" class="boundary">x</div>
  <div id="t2" class="tok">B</div>
  <div id="b2" class="boundary">x</div>
  <div id="t3" class="tok">C</div>
</div>


Solution

  • I'm leaving an answer rather than deleting the question, in case someone else makes a similar mistake: the .draggable() should be invoked after the relevant elements exist, so placing that in $(document).ready or making sure the relevant HTML part is already serialized is necessary.

    The code snippet in this question demonstrates a selectable containing unselectable elements which are draggable - this example might be useful to others, since I was not able to easily find such an example.