Live Demo
Pure JS. Basically just gets the offsets, and does a standard distance check.
//setup for the example
var divs = document.getElementsByTagName('div');
// Randomly place some divs around the screen.
for(var i = 0; i < divs.length; i++){
divs[i].style.top = Math.random()*500 + 'px';
divs[i].style.left = Math.random()*600 + 'px';
divs[i].onclick = getClosest;
}
// Actual function to get the closest
function getClosest(e){
var x = this.offsetLeft,
y = this.offsetTop,
minDist = 99999,
closestElement = {};
for(var i = 0; i < divs.length; i++){
if(divs[i] !== this){
var x2 = divs[i].offsetLeft,
y2 = divs[i].offsetTop;
dist = Math.sqrt((x2 - x) *(x2-x) + (y2 - y) * (y2-y));
if(dist < minDist){
minDist = dist;
closestElement = divs[i];
}
}
}
// Set the background of the closest element to red.
closestElement.style.background = 'red';
}
This is based on the origin being in the top left, but you could change it to the middle of the element by just doing something like the following
x = offsetLeft + width/2;
y = offsetTop + height/2;