Here is a demonstration that I have posted for you to view. The demo showcases the cycling through each droppable position, highlighting that with numerous positions, it may result in slower mouse movement.
In addition, I have included two adjustable variables - xmargin
and ymargin
- which can be modified to increase or decrease the proximity to the droppable area.
CSS
.draggable { width: 100px; height: 100px; padding: 0.5em; position: absolute; top: 0; left: 0; z-index: 2; }
.droppable { width: 150px; height: 150px; padding: 0.5em; position: absolute; z-index: 1; }
#drop1 { top: 200px; left: 250px; }
#drop2 { top: 450px; left: 50px; }
HTML
<div class="draggable ui-widget-content">
<p>Drag me towards my target</p>
</div>
<div id="drop1" class="droppable ui-widget-header">
<p>Drop objects here</p>
</div>
<div id="drop2" class="droppable ui-widget-header">
<p>Place items here</p>
</div>
Script
$(function(){
var xmargin = 15,
ymargin = 15,
drag = $('.draggable'),
drop = $('.droppable'),
dgw = drag.outerWidth() + xmargin,
dgh = drag.outerHeight() + ymargin,
pos = [];
drop
.droppable({
//hoverClass: 'ui-state-active',
drop: function(event, ui) {
$(this).addClass('ui-state-highlight').find('p').html('Object Dropped!');
}
})
// set up coordinates array (left, top, right, bottom) for each droppable element
.each(function(i){
var dropzone = drop.eq(i);
var l = dropzone.position().left,
t = dropzone.position().top,
r = l + dropzone.outerWidth() + xmargin,
b = t + dropzone.outerHeight() + ymargin;
pos.push([l,t,r,b]);
});
drag
.draggable()
.bind( "drag", function(event,ui){
var l = ui.offset.left,
t = ui.offset.top;
drop.each(function(i){
if ( ( l + dgw ) > pos[i][0] && l < pos[i][2] && ( t + dgh ) > pos[i][1] && t < pos[i][3] ) {
$(this).addClass('ui-state-active');
} else {
$(this).removeClass('ui-state-active');
}
});
});
});