Alko Alko - 4 months ago 53x
jQuery Question

jQuery Draggable, convert position to percentage

I'm not sure how to do this. Im using jQuery draggable, and I need to capture grid position:

$("#draggable .item").draggable({
containment: "#dragablle",
snap: '.gridlines',
stop: function(event, ui) {

Looking at the object receiver from stop event :

Object { top=178, left=950}

I need to convert top and left values into percentage, so I can apply to .item element as inline style. Parent "#draggable" width and height will be dynamic, so that's why I need percentage instead of pixel. So when screen is resized, everything will remain the same (position) within parent element


If you are using jQueryUI Draggable

Try this:

 $("#draggable .item").draggable({
  containment: "#dragablle",
  snap: '.gridlines',
stop: function (){
 var l = ( 100 * parseFloat($(this).position().left / parseFloat($(this).parent().width()) )+ "%" ;
 var t = ( 100 * parseFloat($(this).position().top / parseFloat($(this).parent().height()) )+ "%" ;
 $(this).css("left", l);
 $(this).css("top", t)