I want to add some div
using drag and drop mechanism. I have a main div in which I add some other: When I drag div
texted "HI" into below div
, I append two other div
s called Drag and Drop into the main div
.
Now what I want is to have the ability to drag the div
texted "Drag", and drop it into div
texted "Drop". How can I achieve that?
Here is my code:
$(function() {
$(".draggable").draggable({
revert: true,
helper: 'clone',
start: function(event, ui) {
$(this).fadeTo('fast', 0.5);
},
stop: function(event, ui) {
$(this).fadeTo(0, 1);
}
});
$("#div2").draggable({
start: function(event, ui) {
alert('div2-drag');
$(this).fadeTo('fast', 0.5);
},
stop: function(event, ui) {
$(this).fadeTo(0, 1);
}
});
$("#div1").droppable({
hoverClass: 'active',
drop: function(event, ui) {
alert('div1-drop');
//this.value = $(ui.draggable).text();
$("#mydiv").append('<div id="div1" ></div><div id="div2" ></div> ');
}
});
$("#mydiv").droppable({
hoverClass: 'active',
drop: function(event, ui) {
alert('mydiv - drop');
//this.value = $(ui.draggable).text();
$("#mydiv").append('<div id="div1" > Drop</div><div id="div2" ondragstart="drag(event)" > Drag</div> ');
}
});
$("#mydiv_second").droppable({
hoverClass: 'active',
drop: function(event, ui) {
alert('mydivsecond- drop');
//this.value = $(ui.draggable).text();
$("#mydiv_second").append('<div id="div1" > Drop</div><div id="div2" ondragstart="drag(event)" > Drag</div> ');
}
});
});
body {
font-family: sans-serif;
font-size: 11pt;
}
.draggable {
width: 250px;
height: 20px;
background-color: #e6eaff;
border: 2px solid #3399cc;
margin-bottom: 1em;
padding: 4px;
cursor: default;
}
.active {
border: 2px solid #6699ff;
}
#mydiv {
width: 350px;
height: 300px;
background-color: #e6eaff;
border: 2px solid #3399cc;
margin-bottom: 1em;
padding: 4px;
cursor: default;
}
#mydiv_second {
width: 350px;
height: 300px;
background-color: #e6eaff;
border: 2px solid #3399cc;
margin-bottom: 1em;
padding: 4px;
cursor: default;
}
#div1 {
width: 150px;
height: 70px;
background-color: #e6eaff;
border: 2px solid #3399cc;
margin-bottom: 1em;
padding: 4px;
cursor: default;
}
#div2 {
width: 30px;
height: 30px;
background-color: #e6eaff;
border: 2px solid #3399cc;
margin-bottom: 1em;
padding: 4px;
cursor: move;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<div class="draggable">hi!</div>
<div id="mydiv"></div>
<div id="mydiv_second"></div>
You can also see it on this jsFiddle