Page 1 of 1
jQuery - Find distance between two DIVs
Posted: 03 Jan 2015, 16:35
by MarPlo
I have two DIVs that I need to know the calculated browser distance (in width and height) of them.
Example html:
Code: Select all
<div id="dv1">div 1</div>
<div id="dv2">div 2</div>
I want to know the horizontal and vertical distances between these two (in pixels), using jQuery.
jQuery - Find distance between two DIVs
Posted: 03 Jan 2015, 16:53
by Admin
Use the offset() function.
Something like this should work:
Code: Select all
<div id="dv1">div 1</div>
Some text ...<br>
https://coursesweb.net/
<div id="dv2">div 2</div>
<script>
var dist_ho = Math.abs($('#dv1').offset().left - $('#dv2').offset().left); // horizontal distance
var dist_ve = Math.abs($('#dv1').offset().top - $('#dv2').offset().top); // vertical distance
// test
alert('dist_ho: '+ dist_ho + ' - dist_ve: '+ dist_ve);
</script>
-The Math.abs() methods is used to have positive values.