javascript - Positioning a draggable at the parent's center -


i want position draggable div within divs parents center. see example here

$("#mover").draggable({     revert: true,     containment: "parent" });  <div style="width: 100px; height: 100px;" id="joystick">     <div style="width: 10px; height: 10px" id="mover"></div><br /> </div> 

now, works fine, want position mover @ joysticks center, dragging doesn't work way want to.

i tried positioning giving mover margin: 45px 0 0 45px;, (because of box-model seeing margin part of box) dragging still works down , right, , not , left.

as see, want create kind of "joystick" used steer something. therefore, needs centered but movable in axis'.

any ideas highly appreciated.

here's full working demo, have position center of joystick position:relative;: http://jsfiddle.net/e6bqe/

html:

<div id="coords">&nbsp;</div> <div id="joystick">     <div id="mover"></div> </div> 

css:

#joystick { background-color:whitesmoke; width: 100px; height: 100px; padding:0px; } #mover { background-color:red; position:relative; margin:0px; padding:0px; width: 10px; height: 10px; left:45px; top:45px; } 

javascript:

$("#mover").draggable({     revert: true,     containment: "parent",     create: function(){         $(this).data("startleft",parseint($(this).css("left")));         $(this).data("starttop",parseint($(this).css("top")));     },     drag: function(event,ui){         var rel_left = ui.position.left - parseint($(this).data("startleft"));         var rel_top = ui.position.top - parseint($(this).data("starttop"));         $('#coords').text(rel_left + ", " + rel_top);     },     stop: function(){         $('#coords').html("&nbsp;");     } }); 

Comments