How to get position of element in jquery

If you want to get position of an element of div tag, jquery provides two different functions for this.

  • position()

    This function provides top and left position of an element with respect to its parent.

  • offset()

    This function provides top and left position of an element with respect to the page or document.

HTML & Script
<div id="containerelem" style="margin: 10px;  position:relative;">
    <button id="child1" class="btn">
    </button>
    <button id="child2" class="btn" style="position: absolute; top: 200px; left: 400px;">
    </button>
</div>
<script type="text/javascript">
    $("#child1").html("Position - top : " + $("#child1").position().top + ", left : " + $("#child1").position().left + "<br/>Offset - top : " + $("#child1").offset().top + ", left : " + $("#child1").offset().left);
    $("#child2").html("Position - top : " + $("#child2").position().top + ", left : " + $("#child2").position().left + "<br/>Offset - top : " + $("#child2").offset().top + ", left : " + $("#child2").offset().left);
</script>

Ideally position() should be used while placing two element beside each other. One of the example where offset() has been used is photozoom plugin.

If you have any questions regarding position or offset please ask in the comment box below. I will be happy to answer your queries.
Subscribe for our monthly newsletter for updated articles and useful code scripts.

Share It

comments powered by Disqus
Chat With Us Close
Leave Message