Adityo Setyonugroho
Adityo Setyonugroho

Reputation: 897

Draggable and Droppable Jquery UI Switch Position

I am learning Jquery Draggable and Droppable right now. I would like to create switchable content. I have this scheme:

<div class="droppableContainer">
  
  <div class="draggableContent" id="Content1">
    Hi I am Content 1.
  </div>
  
</div>


<div class="droppableContainer">
  
  <div class="draggableContent" id="Content2">
    Hi I am Content 2.
  </div>
  
</div>

If, I drag my Content1 and drop it into another droppableContainer, I would like to switch it with Content2. So after I dropped Content1, Content2 move to the Content1 droppableContainer like shown below.

<div class="droppableContainer">
  
  <div class="draggableContent" id="Content2">
    Hi I am Content 2.
  </div>
  
</div>


<div class="droppableContainer">
  
  <div class="draggableContent" id="Content1">
    Hi I am Content 1.
  </div>
  
</div>

Any suggestion to do it ? Thanks

Upvotes: 2

Views: 134

Answers (1)

Adriana Hern&#225;ndez
Adriana Hern&#225;ndez

Reputation: 1065

I solved this using sortable().

First, you need to wrap your draggable items inside a single container, like this:

<div class="droppableContainer">
  <div class="draggableContent" id="Content2">
    Hi I am Content 2.
  </div>
  <div class="draggableContent" id="Content1">
    Hi I am Content 1.
  </div>
</div>

And add this js:

$(".droppableContainer").sortable({
    distance: 20, //distance is optional. This indicates the number of pixels that the mouse must be moved before the sorting starts.
    placeholder: "highlight"
}); 
$( ".droppableContainer" ).disableSelection(); 

Then, optionally you can style your highlight class with some CSS if you want to make it look like this example.

You can check this demo I made in Codepen

Upvotes: 0

Related Questions