javascript - How to move a second div at the same rate as first div jquery UI dragged? -


if have 2 <divs>, , b separate divs absolute positioned. if drag div b, can move anywhere. if drag a, div b move same offset moved div a.

what know far this, however, despite being able place div b anywhere want. upon moving div a, div b snaps place next div a..

$('.a, .b').draggable({     drag: function(event, ui) {         $('.a').css({             top: ui.offset.top + 'px',             left: ui.offset.left + 100 + 'px'         });     } }); 

is there way can add kind of "mouseoffset" make work?

try this:

$(function(){     $('.a, .b').draggable({         start: function(){             if($(this).hasclass('b')){                 var p = $(this).position();                 $(this).data('lastleft',p.left);                 $(this).data('lasttop',p.top);             }         },         stop: function(){             if($(this).hasclass('b')){                 $(this).removedata('lastleft');                 $(this).removedata('lasttop');             }         },         drag: function(event, ui) {             if($(this).hasclass('b')){                 var p = $(this).position();                 $(this).data('lastleft',p.left);                 $(this).data('lasttop',p.top);                  var dx = ui.position.left - $(this).data('lastleft');                 var dy = ui.position.top - $(this).data('lasttop');                 $('.a').each(function(){                     var p = $(this).position();                     $(this).css({                         left: (p.left + dx) + "px",                         top: (p.top + dy) + "px"                     });                 });             }         }     }); }); 

working jsfiddle demo: http://jsfiddle.net/dkjfh/1/

it saves start position of b on every mousemove can calculate offset next time.


Comments