Random Channel
Random Channel

Reputation: 1164

Drag and drop swap using jQuery

I was wondering how to do a drag and drop swap with jQuery. I have 3 parent divs, and I have 2 child divs. I want the child divs to be droppable in a parent div without a child div, but I don't want any parent div to be able to store 2 child divs. If a child div is being dragged into a parent div with a child div, I want the two child divs to swap. I am fine with using jQuery UI, because the following code contains it.

$("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
 }
 #child1 {
   height: 50px;
   width: 50px;
   background-color: khaki;
 }
 #child2 {
   height: 50px;
   width: 50px;
   background-color: aqua;
 }
<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" id="child1"></div>
</div>
<div class="parent">
  <div class="child" id="child2"></div>
</div>
<div class="parent">
</div>

Any help, especially in code form, would be highly appreciated.

jsfiddle: https://jsfiddle.net/g2efds1z/10/

Upvotes: 3

Views: 3707

Answers (1)

user372495
user372495

Reputation: 710

Well, you have to move the elements already inside one to the other, so I would begin by having code like this inside your drop function:

if ($(this).children().length > 0) {
  var move = $(this).children().detach();
  $(ui.draggable).parent().append(move);
}

this added into the whole code:

$("document").ready(function() {
  $(".child").draggable({
    revert: true
  });
  $(".parent").droppable({
    accept: '.child',
    drop: function(event, ui) {
    if ($(this).children().length > 0) {
      var move = $(this).children().detach();
      $(ui.draggable).parent().append(move);
    }

      $(this).append($(ui.draggable));
    }
  });
});
.parent {
   float: left;
   margin-left: 5px;
   height: 200px;
   width: 200px;
   border: 3px solid black
 }
 #child1 {
   height: 50px;
   width: 50px;
   background-color: khaki;
 }
 #child2 {
   height: 50px;
   width: 50px;
   background-color: aqua;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>      
<div class="parent">
  <div class="child" id="child1"></div>
</div>
<div class="parent">
  <div class="child" id="child2"></div>
</div>
<div class="parent">
</div>

Upvotes: 3

Related Questions