jQuery .position() absolute or position relative to the parent

The .position() method gets the position of an element relative to the offset parent or gets the absolute position of the element. Also check jQuery .offset().

Code:

<script>
$(function(){
    var position = $('.target').position();
    $('.target').append( ": left=" + position.left + ", top=" + position.top );
 
    var position_absolute = $('.target-absolute').position();
    $('.target-absolute').append( ": left=" + position_absolute.left + ", top=" + position_absolute.top );
});</script>
<style>
.parent {
    padding:20px;
    margin:8px;
}
.target {
    margin:15px;
    padding:3px;
}
 
.parent-relative {
    position:relative;
}
.target-absolute {
    margin:20px;
    padding:3px;
    position:absolute;
    left:10px;
    top:5px;
}
​
</style>
<div class="parent"><h3 class="target">get position relative to the offset parent with jQuery</h3></div>
<div class="parent-relative"><h3 class="target-absolute">get absolute position of the element with jQuery</h3></div>

Leave a Reply

Your email address will not be published. Required fields are marked *