Jquery disables droppable after it reaches 3 element limit

I have two lists that drag and drop. I want my second list to display only three list items from the first list. My problem is that when I reach the limit, the counter works, but I get this error:

Unused error: it is impossible to call drag and drop methods before initialization; tried to call the disable method

and it allows you to drag more than three elements. I would like it to focus on 3 elements, and when I pull from the second list, this is minus the counter.

var counter = 0;

$("#listbox2").droppable({
    drop: function(event, ui) {
        if (counter <= 3) {
            counter++;
            $('#counter_text').text(counter);
        }
        if (counter === 3) {
            $('#listbox2').droppable("disable");
            $('#listbox1 li').draggable("disable");
        }
    }
})

$("#listbox1").droppable({
    drop: function(event, ui) {
        counter--;
        $('#counter_text').text(counter);

    }
})
+4
source share
3 answers

. ( , BTW)

var counter = 0;
$('#counter_text').text(counter);    

$('#listbox1 li').draggable({
  stop: function(event, ui) {
    $(this).css('left',0);
    $(this).css('top',0);
  }
});

$("#listbox2").droppable({
  drop: function(event, ui) {
    $(this).append(ui.draggable);
    if (counter <= 3) {
      counter++;
      $('#counter_text').text(counter);
    }
    if (counter === 3) {
      $('#listbox2').droppable("disable");
      $('#listbox1 li').draggable("disable");
    }
  },
  hoverClass: 'hover'
});

$("#listbox1").droppable({
  drop: function(event, ui) {
    counter--;
    if (counter<3) {
      $("li").draggable("enable");  
      $('#listbox2').droppable("enable");
    }
    $('#counter_text').text(counter);    
    $(this).append(ui.draggable);
    $(ui.draggable).draggable('enable');
  },
  hoverClass: 'hover'
});
ul {
  border: solid 1px green;
  padding: 5px;
  height: 120px;
}

.hover {
  background-color: #CFC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>

<div id="counter_text"></div>

<ul id="listbox1">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>

<ul id="listbox2">
</ul>
Hide result
+2

: , (: $('#listbox1 li').draggable();), - .

+1

Inside the drop function, if you do:

 $('#list1').droppable("disable");
 $('#list2 li').draggable("disable");

You'll get:

Unprepared error: it is impossible to call drag and drop methods before initialization; tried to call the disable method

I suggest you do the same in timout funtion, like this:

if ($('#list1 li').length >= 3) {
        window.setTimeout(function() {
          $('#list1').droppable("disable");
          $('#list2 li').draggable("disable");
        }, 100)
        return false;
      }

working example here

0
source

Source: https://habr.com/ru/post/1628084/


All Articles