Search code examples
jqueryposition

JQuery get left and top positions from div based on parent div


I have a draggable divs inside another div and need to get the left and top positions from child div.

<div id="parent">
<div id="child1" style="position:absolute;"></div>
<div id="child1" style="position:absolute;"></div>
</div>

At the moment i get the positions from childs based on the first placement:

$('#iframe_main').contents().find('.button".$key."').draggable({ 
    containment:'#parent',
    scroll: false,
    drag: function(event) {
        o = $('#iframe_main').contents().find('.child').offset();
        p = $('#iframe_main').contents().find('.child').position();

}});

So if i place the child in the right bottom corner of #parent and move it back to the left top corner i get negativ values.

What i want is the left and top postion from child divs based on #parent div.


Solution

  • You need to calculate the position of both element. Please see below.

    This is an example what you can make.

    $('#iframe_main').contents().find('.button".$key."').draggable({ 
        containment:'#parent',
        scroll: false,
        drag: function(event) {
            o = $('#iframe_main').contents().find('.child').offset();
            p = $('#iframe_main').contents().find('#parent').offset();
    
            childtop = o.top - p.top;
            childleft = o.left - p.left;
            console.log(childtop + " " + childleft);
    
    }});