Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drag and insert div into another div

I am trying to design a feature that could drag and insert one div into another div.

For example:

<div id="1"> </div>
<div id="2"> </div>

i want to make #1 draggable (I know it can be done with jQuery, so draggable is not part of my question), and drag #1 over #2, and when mouseup, #2 could be inserted into #1

<div id="1"> <div id="2"> </div> </div>

could somebody explain to me how to achieve that?

like image 522
user2640254 Avatar asked Aug 03 '13 09:08

user2640254


2 Answers

You could simplify this quite a bit by using jQuery UI's Sortable

Working Example

$(document).ready(function () {
    addElements();
    $(function () {
        $("#list1, #list2").sortable({
            connectWith: ".lists",
            cursor: "move"
        }).disableSelection();
    });


});

function addElements() {
    $("#list1").empty().append(
        "<li id='item1' class='list1Items'>Item 1</li>" +
        "<li id='item2' class='list1Items'>Item 2</li>" +
        "<li id='item3' class='list1Items'>Item 3</li>");
}
like image 126
apaul Avatar answered Sep 29 '22 20:09

apaul


For demo : Click Here

Code :

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Droppable - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <style>
  #draggable { width: 100px; height: 100px; padding: 0.5em; float: left; margin: 10px 10px 10px 0; }
  #droppable { width: 150px; height: 150px; padding: 0.5em; float: left; margin: 10px; }
  </style>
  <script>
  $(function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
      }
    });
  });
  </script>
</head>
<body>

<div id="draggable" class="ui-widget-content">
  <p>Drag me to my target</p>
</div>

<div id="droppable" class="ui-widget-header">
  <p>Drop here</p>
</div>


</body>
</html>
like image 31
Butani Vijay Avatar answered Sep 29 '22 18:09

Butani Vijay