Home > Net >  Function on created jquery droppable element
Function on created jquery droppable element

Time:09-29

Please tell me why the droppable function does not work on the added drop elements and how to solve this problem?

$(function() {
  $(".drag").draggable({
    start: function(event, ui) {
      $(".to_drop").append('<div class="drop">New</div>');
    },
    stop: function(event, ui) {

    },
  });
  $(".drop").droppable({
    revert: "valid",
    drop: function(event, ui) {
      alert(1);
    }
  });
});
.drag {
  width: 50px;
  height: 50px;
  background: blue;
}

.drop {
  width: 100px;
  height: 100px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="drag"></div>
<div class="to_drop">
  <div class="drop">Old</div>
</div>

CodePudding user response:

When you run $(".drop").droppable the new .drop doesn't exist yet. You can just re-run after creating the new div on just the new div:

$(function() {
  $(".drag").draggable({
    start: function(event, ui) {
      const $dropper = $($.parseHTML('<div class="drop">New</div>'))
      $(".to_drop").append($dropper);
      $dropper.droppable({
          revert: "valid",
          drop: function(event, ui) {
              alert(1);
          }
      });
    },
    stop: function(event, ui) {

    },
  });
  $(".drop").droppable({
    revert: "valid",
    drop: function(event, ui) {
      alert(1);
    }
  });
});
.drag {
  width: 50px;
  height: 50px;
  background: blue;
}

.drop {
  width: 100px;
  height: 100px;
  border: 1px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="drag"></div>
<div class="to_drop">
  <div class="drop">Old</div>
</div>

  • Related