I am trying to create a drag and drop function for my website without using jQuery UI or the HTML5 drag drop functions. I have figured out the drag part but I am unable to drop them in specific drop areas. here is my code:
HTML
<ul id="grid">
<li class="drop">
<div class="drag" id="el_1"><div>
</li>
<li class="drop">
<div class="drag" id="el_2"><div>
</li>
<li class="drop">
<div class="drag" id="el_3"><div>
</li>
<li class="drop"></li>
<li class="drop"></li>
<li class="drop"></li>
</ul>
<script>
$(function() {
$('.handle').mousedown(drag_and_drop);
});
</script>
CSS
#grid{
position:relative;
width:360px;
height:auto;
}
.drop{
width:100px;
height:100px;
margin:10px;
}
.drag{
position:absolute;
width:100px;
height:100px;
}
#el_1{ top:10px; left:10px}
#el_2{ top:10px; left:130px}
#el_3{ top:10px; left:250px}
SCRIPT
function drag_and_drop(e){
var drag = $(this);
var drop = drag.parent();
drag.addClass('draggable');
drag_h = drag.outerHeight(),
drag_w = drag.outerWidth(),
pos_y = drag.offset().top + drag_h - e.pageY,
pos_x = drag.offset().left + drag_w - e.pageX;
$('.draggable').css('z-index', 9000).mousemove(function(e) {
/*
IN THIS MOUSEMOVE FUNCTION IS THERE ANY WAY TO DETECT IF THE DRAGGABLE DIV IS "HOVERING" OVER THE li.drop ELEMENTS?
*/
$('.draggable').offset({
top: e.pageY + pos_y - drag_h,
left: e.pageX + pos_x - drag_w
});
}).mouseup(function() {
drag.removeClass('draggable');
});
e.preventDefault(); // stops the browser default drag method
};
Is there any way that once I have started to drag an object that it can detect if it is over a specific li.drop – from which I will be able to drop it into?
you could use the below to get the current mouse position and write another function to see if that position is within a droppable divs bounds. good article here:
http://docs.jquery.com/Tutorials:Mouse_Position#How_do_I_find_the_mouse_position.3F