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.