Ad

How To Make Drag And Drop Jquery?

- 1 answer

I've been wondering how to make drag and drop with jQuery, because it is difficult to use the javascript drag and drop, and I prefer to use jQuery instead of javascript. What I want is for the child div to be draggable, and only be droppable in the parent divs. When the child div is dropped, if it is not in a parent div, then it will revert back to the last parent div it was in. if the child div was dropped in a parent div, then it will go to the top left corner of the parent div it was dropped in. The child div is only draggable. I am fine with using jQuery UI, but I couldn't get the .droppable() function to work.

HTML:

<div id="div1" class="div">
<div id="image" class="image"></div>
</div>
<div id="div2" class="div">
</div>

CSS:

.div {
     float: left;
     margin-left: 5px;
     height: 200px;
     width: 200px;
     border: 3px solid black
        }
.image {
      height: 50px;
      width: 50px;
      background-color: khaki;
    }

jQuery (only drag):

    $("document").ready(function() {
    $(".image").draggable();
});

jsfiddle: https://jsfiddle.net/j9pvbuue/8/ I would highly appreciate if you could directly give me a code for the answer, instead of indirect answers that tell me nothing of how to use it.

Ad

Answer

jQuery has no draggable API.

You can use jQuery UI draggable and jQuery UI droppable OR use HTML5Drag and Drop API.

Update

According to updated description of the original question, demo solution code:

$("document").ready(function() {
  $(".child").draggable({
    revert: true
  });

  $(".parent").droppable({
    accept: '.child',
    drop: function(event, ui) {
      $(this).append($(ui.draggable));
    }
  });
});
 .parent {
   float: left;
   margin-left: 5px;
   height: 200px;
   width: 200px;
   border: 3px solid black
 }
 .child {
   height: 50px;
   width: 50px;
   background-color: khaki;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>


<div class="parent">
  <div class="child"></div>
</div>
<div class="parent">
</div>
<div class="parent">
</div>

Ad
source: stackoverflow.com
Ad