Search code examples
jqueryjquery-uidrag-and-dropjquery-ui-draggable

jQuery 2D drag and drop element (Not absolute position)


I am going put external element into inner html using drag & drop. So I assume like this. This is inner html.

<div class="inner_html">
   <div class="title">
     <h1>This is title</h1>
   </div>
   <div class="body">
     <li>this is element</li>
     <a>element</a>
   </div>
</div>

Here is external html. <div>This is external element</div>

I am going to drag external element and drop into inner html. So final element can get a lot of results. I think if position were absolute, then it can be done easily using jquery draggable plugin. But I don't want absolute position. just want to put into inner html.

Can anyone help me?


Solution

  • Consider the following code.

    $(function() {
      $(".drag > div").draggable();
      $(".inner_html").droppable({
        drop: function(e, ui) {
          ui.draggable.css({
            top: "",
            left: "",
            position: "inherit"
          }).appendTo($(".inner_html"));
        }
      });
    });
    .inner_html {
      width: 340px;
      background: #ccc;
      padding: 1em;
      margin-bottom: 20px;
    }
    
    .inner_html>div {
      background: white;
      border: 1px solid #222;
      border-radius: 3px;
    }
    
    .drag {
      border: 1px solid #ccc;
      width: 340px;
    }
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <div class="inner_html">
      <div class="title">
        <h1>This is title</h1>
      </div>
      <div class="body">
        <a>Link</a>
      </div>
    </div>
    <div class="drag items">
      <h3>Items</h3>
      <div>This is external element</div>
    </div>