Find Distance Between Two DIVs Using JQuery?
I have two DIVs that I need to know the calculated browser distance (in height) of them. I have read about the offset feature but the examples were not written for the way I am try
Solution 1:
Something like this should work:
$('.foo').offset().top - $('.bar').offset().top
As long as each class only has one element on the page.
If they are not unique, give the two elements an ID and reference with that.
Solution 2:
Use .offset()
:
$('.foo').offset().top - $('.bar').offset().top
Solution 3:
This function finds the distance in pixels between the centre of two elements, no jquery:
function distanceBetweenElems(elem1, elem2) {
var e1Rect = elem1.getBoundingClientRect();
var e2Rect = elem2.getBoundingClientRect();
var dx = (e1Rect.left+(e1Rect.right-e1Rect.left)/2) - (e2Rect.left+(e2Rect.right-e2Rect.left)/2);
var dy = (e1Rect.top+(e1Rect.bottom-e1Rect.top)/2) - (e2Rect.top+(e2Rect.bottom-e2Rect.top)/2);
var dist = Math.sqrt(dx * dx + dy * dy);
return dist;
}
I use it like this:
var target1 = document.querySelector('#foo');
var target2 = document.querySelector('#bar');
if (distanceBetweenElems(target1,target2)<100){
target1.classList.add('active');
}
Post a Comment for "Find Distance Between Two DIVs Using JQuery?"