In this tutorial, you will learn how to calculate or get the distance between two div elements in JavaScript.
We can do it by some JavaScript method or function.
Get the distance between two div elements in JavaScript.
let’s learn this with code explanation.
step-1
<script> document.addEventListener('DOMContentLoaded', function() { //rest of the code }) </script>
This ” document.addEventListener(‘DOMContentLoaded’, function() { “ function waits until the DOM/HTML page gets fully loaded, all the other functions of the code come under this function, so they get executed after the page loaded.
step-2
let distance1 = document.getElementById('distance1'); let distance2 = document.getElementById('distance2');
here we store the “ ID “ of two div elements in the variables ” distance1, distance2 ” for targeting them.
step-3
let distance1Rect = distance1.getBoundingClientRect(); let distance2Rect = distance2.getBoundingClientRect();
these lines get the position and the dimensions of each element and store them in “distance1Rect” and “distance2Rect”. these rectangles contain properties like ‘top’, ‘bottom’, ‘left’, ‘right’, ‘width’ and ‘height’.
step-4
let distanceX = Math.abs(distance1Rect.left - distance2Rect.left); let distanceY = Math.abs(distance1Rect.top - distance2Rect.top);
these parts calculate the horizontal and vertical distance between the left/top edges of the two elements. The ‘Math.abs’ is used to make the values positive.
step-5
let distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
these parts calculate the distance of the two div element by “Pythagorean theorem” the formula is “(c= sqrt (a^2 + b^2))”.
step-6
bt.addEventListener('click',function(){ d[1].innerHTML=distance })
At the end display the distance on the page by Butten click.
Full JavaScript code is here.
<script> document.addEventListener('DOMContentLoaded', function() { let bt=document.querySelector('#bt'); let d=document.querySelectorAll('.d'); let distance1 = document.getElementById('distance1'); let distance2 = document.getElementById('distance2'); let distance1Rect = distance1.getBoundingClientRect(); let distance2Rect = distance2.getBoundingClientRect(); let distanceX = Math.abs(distance1Rect.left - distance2Rect.left); let distanceY = Math.abs(distance1Rect.top - distance2Rect.top); let distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY); bt.addEventListener('click',function(){ d[1].innerHTML=distance }) }) </script>
Check it out here:
Click Here