I need a little help please. I need to have a blue circle, a red circle, a blue square and a red square. I need to drag the red circle to the center of the red square and the blue circle to the center of the blue square. Unless I drag it to the correct position, it should revert to original position.
This is what I have so far:
$("#draggable, #draggable2").draggable({
revert: 'invalid', snap: "#droppable2"
});
$("#droppable").droppable({
accept: '#draggable'
});
$("#droppable2").droppable({
accept: '#draggable2',
});
http://jsfiddle.net/tM7cp/269/
I can't position them the circles to the center of the squares, how can I do that?
You can manually snap the items to the center of droppables using jQuery Ui's position()
utility method as follows (I changed your logic slightly to avoid repetition of code and CSS):
$(".draggable").draggable({
revert: 'invalid'
});
$(".droppable").droppable({
accept: function(item) {
return $(this).data("color") == item.data("color");
},
drop: function(event, ui) {
var $this = $(this);
ui.draggable.position({
my: "center",
at: "center",
of: $this,
using: function(pos) {
$(this).animate(pos, 200, "linear");
}
});
}
});
.draggable {
float: left;
width: 100px;
height: 100px;
padding: 0.5em;
margin: 10px 10px 10px 0;
border: 1px solid black;
border-radius: 50%;
}
#draggable {
background-color: red;
}
#draggable2 {
background-color: blue;
}
.droppable {
padding: 0.5em;
float: left;
margin: 10px;
}
#droppable {
width: 100px;
height: 100px;
background-color: red;
}
#droppable2 {
width: 120px;
height: 120px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<div id="draggable" class="draggable" data-color="red"></div>
<div id="draggable2" class="draggable" data-color="blue"></div>
<div id="droppable" class="droppable" data-color="red"></div>
<div id="droppable2" class="droppable" data-color="blue"></div>