supersize
supersize

Reputation: 14783

get distance from dragged element to other related element

I might have a very specific question about jQuery's draggable() in combination with css. I have lots of divs in my body which are all draggable:

for(var i = 0; i < 150; i++) {
        var randomleft = Math.floor(Math.random()*1000);
        var randomtop = Math.floor(Math.random()*1000);
        var appenditem = '<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>'
        $('body').append(appenditem);
        cubes.push($('#cube'+i));
    }

$('div').draggable();

So far so good.

Then I have a fixed <div id="fixed"> in my body at a specific position, lets say: top: 50px; left: 50px;

What I would like to do is trigger the event handler on dragstop and get the distance between the currently dragged div on dragstop to the fixed div.

For example on dragend a div is dragged to: top: 500px; left: 40px then I would like to have the values: +450 and -10 because the div was top: +450px and -10px from #fixed.

How can I do this, and especially the negative value.

Thanks in advance

Upvotes: 1

Views: 412

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206209

LIVE DEMO

jQuery(function($) {

   var allCubes  = '',
       $fixed    = $('#fixed'),
       fixedOffs = $fixed.offset();

    for(var i = 0; i < 150; i++) {
        var randomleft = Math.floor(Math.random()*1000),
            randomtop  = Math.floor(Math.random()*1000);
        allCubes += '<div id="cube'+i+'" style="position: absolute; border: 2px #000 solid; left: '+randomleft+'px; top: '+randomtop+'px; width: 15px; height: 15px;"></div>';
    }  

    $('body').append(allCubes); // Outside loop! (60% more performance)

    $('[id^="cube"]').draggable({
        stop: function(ev, ui){
            var pos = ui.position; // or use ui.offset if you need document related position
            // var orgPos = ui.originalPosition; // if you need it
            alert(
               ( pos.left - fixedOffs.left )+' \n '+
               ( pos.top  - fixedOffs.top  )
            );
        }
    });  

});

Upvotes: 2

nietonfir
nietonfir

Reputation: 4881

As you're using jQuery, all you need is the offset() of your fixed element. The draggable ui object in the stop callback provides this information as well, the rest is simple math:

// assuming the stop callback of draggable()
stop: function( event, ui ) {
    var fixedOffset = $("#fixed").offset();

    return {
        top: ui.offset.top - fixedOffset.top,
        left: ui.offset.left - fixedOffset.left,
    }
}

With the values of your example this function would return an object literal with the following values: { top: 450, left: -10 }

Upvotes: 0

Related Questions