I am wondering what's the best solution for this. Return and show the nearest hyperlink on a webpage when the mouse is clicked.
There are 3 DIV
s in this example. each of them carries a hyperlink inside. There's also another hyperlink (hyperlink D) by itself without a DIV
. And lets say the red dot is mouse click.
For Example
The solution I can think of is just iterate through all the links by doing
var a_list = document.getElementsByTagName("a");
and then compute the distance by using distance equation c^2 = a^2 + b^2
, so simply
var a_list = Array.prototype.slice.call(document.getElementsByTagName("a"))
for( var i = 0 ; i < a_list.length; i++){
Math.sqrt(Math.pow(mouseX - a_list[i].getBoundingClientRect().left,2) +
Math.pow(mouseY - a_list[i].getBoundingClientRect().top,2))
}
This approach certainly takes about O(N) time complexity where N is the number of links that we have. Can we do better ?