Razin223
Razin223

Reputation: 50

Getting Position of a div respected to another div in jquery

I'm trying to get the top and left position regards to its parent document. I tried using offset and position. Offset not working at all and position giving me different values. Here is my codes

<style>
.item{
            width: 30px;
            height: 30px;
            border: solid black 1px;
            cursor: move;
        }
        #item-1{
            position: relative;
            background-color: red;
        }
        #item-2{
            background-color: yellow;
        }
</style>

<div id="image_div" style="border: solid black 1px;position: relative;width: 1024px;height: 460px;overflow: auto">
        <img src="img.jpg"/>
        <div id="fixing_div" style="position:absolute;z-index: 1;background-color: rgba(0,0,0,0.1);top: 0;left: 0;">
            <div id="item-1" class="item"></div><br/>

            <div id="item-2" class="item"></div>
        </div>
    </div>

I want my id="item-1" div's position respected to id="fixing_div" div. How can I get it?

N.B: I'm using jquery ui and item-1 and item-2 both are resizable and dragable. So position will be changed

Upvotes: 0

Views: 29

Answers (1)

apaul
apaul

Reputation: 16170

I'm not to sure how you were trying to do it, but this seems to work:

$('.item').draggable({
    drag: function () {
        $(this).text('top: '+ $(this).position().top + ' left: ' + $(this).position().left);
    }
});
.item {
    width: 30px;
    height: 30px;
    border: solid black 1px;
    cursor: move;
}
#item-1 {
    position: relative;
    background-color: red;
}
#item-2 {
    background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

<div id="image_div" style="border: solid black 1px;position: relative;width: 1024px;height: 460px;overflow: auto">
    <img src="img.jpg" />
    <div id="fixing_div" style="position:absolute;z-index: 1;background-color: rgba(0,0,0,0.1);top: 0;left: 0;">
        <div id="item-1" class="item"></div>
        <br/>
        <div id="item-2" class="item"></div>
    </div>
</div>

Upvotes: 1

Related Questions