Skip to content

Instantly share code, notes, and snippets.

@yaci
Last active March 15, 2021 18:46
Show Gist options
  • Save yaci/b1f4f4aa30bb111becfd267ce941b47b to your computer and use it in GitHub Desktop.
Save yaci/b1f4f4aa30bb111becfd267ce941b47b to your computer and use it in GitHub Desktop.
Measures vertical distance between elements on a page.
/* 1. run the code in the console
* 2. Click on an element on a page
* 3. Click on another element
* 4. Distance between the two will be shown in the console
* NOTE: it measures only vertical distance (Y axis) NOT the horizontal one!
*/
var firstElement;
function measureDistance(firstEl, secondEl) {
const position1 = firstEl.getBoundingClientRect();
const position2 = secondEl.getBoundingClientRect();
const elementsAreTheSame = (firstEl === secondEl);
const oneElementIsChildOfTheOtherOne = (firstEl.contains(secondEl) || secondEl.contains(firstEl)) && !elementsAreTheSame;
const elementsAreNotRelated = !elementsAreTheSame && !oneElementIsChildOfTheOtherOne;
if (elementsAreNotRelated) {
const distance = (position1.top < position2.top) ? position2.top - position1.bottom : position1.top - position2.bottom;
console.log("Distance:", distance);
}
else if (oneElementIsChildOfTheOtherOne) {
const topEdgesDistance = Math.abs(position1.top - position2.top);
const bottomEdgesDistance = Math.abs(position1.bottom - position2.bottom);
console.log("One element contains another");
console.log("Distance between top edges: ", topEdgesDistance);
console.log("Distance between bottom edges:", bottomEdgesDistance);
}
else if (elementsAreTheSame) { //user clicked twice on the same element
console.log("You selected the same element twice. Here are its dimensions:");
console.log("Height:", position1.height);
console.log("Width: ", position1.width);
}
}
function selectElement(clickEvent) {
clickEvent.stopPropagation();
clickEvent.preventDefault();
const selectedEl = clickEvent.target;
if (!firstElement) {
firstElement = selectedEl; //assignment to global variable
console.log("Element 1: ", selectedEl)
}
else {
console.log("Element 2: ", selectedEl);
measureDistance(firstElement, selectedEl);
firstElement = null;
}
}
function addMeasuringEvent(elem) {
elem.addEventListener('mouseover', ev => ev.target.style.backgroundColor = "LightGreen");
elem.addEventListener('mouseout', ev => ev.target.style.backgroundColor = '');
elem.addEventListener('click', selectElement);
}
document.querySelectorAll("body *:not(nextjs-portal,script,svg *)").forEach(e => addMeasuringEvent(e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment