If we want to find the current coordinates of the element then we can easily do that with the help of jQuery. jQuery have offset()
method which makes us to find the coordinates of the element which you want to find in respect to the document.
jQuery offset() method and position() method are different because offset()
method will find the coordinates of the element which you want to find in respect to the document whereas position() method will find the position on basis of the offset parent .
offset()
method will give the position of the element with two properties i.e Top and Left.
Below is the html code for offset() method example :-
<div id="result"> result div</div>
<p>
click any element for getting their coordinates.
</p>
<div class="cords_div">
</div>
Below is the jQuery code for offset() method example :-
$( "*", document.body ).click(function( event ) {
var mthd = $( this ).offset();
event.stopPropagation();
$( "#result" ).text( this.tagName +
" coordinates ( " + mthd.left + ", " + mthd.top + " )" );
});
Below the css for above html code:-
p {
margin: 10px;
color: red;
width: 100%;
}
div.cords_div {
width: 60px;
height: 60px;
position: absolute;
left: 50px;
top: 100px;
background-color: grey;
}
Working demo :-https://jsfiddle.net/c3wvt8g1/5/
0 Comment(s)