JQuery offset position according to containment position

<script>
$(document).ready(function(e) {
    $(function(){
        $( "#draggable" ).draggable({
            containment: "#box",
            drag: function(){
                var offset = $(this).offset();
                var xPos = offset.left;
                var yPos = offset.top;

                $('#posX').val('x: ' + xPos);
                $('#posY').val('y: ' + yPos);
            }
        });
    });
});
</script>

<style>
body{margin:0;}
#draggable{width:100px; height:100px; background:red;}
#box{width:500px; height:500px; border:solid 1px #000; margin:100px;}
</style>
<div id="box">
    <div id="draggable"></div>
</div>
<input id="posX" type="text" />
<input id="posY" type="text" />

      

I have a div using jQuery drag and drop and position detecting.

My question is, how can I get the offset position according to the defense $('#box')

and not according to the document?

+3


source to share


1 answer


When a drag element is added to the body, it is not inside the element #box

at all when dragged, so you need to subtract the position of the containing element, and in your case also the border, to get the correct values

$(function(){
    var box    = $('#box').offset(),
        border = parseInt($('#box').css('border-width').replace(/\D/g,''), 10);

    $( "#draggable" ).draggable({
        containment: "#box",
        drag: function(){
            var offset = $(this).offset();
            var xPos = offset.left - box.left - border;
            var yPos = offset.top - box.top - border;

            $('#posX').val('x: ' + xPos);
            $('#posY').val('y: ' + yPos);
        }
    });
});

      



FIDDLE

+2


source







All Articles