Andrei Zisu Andrei Zisu - 25 days ago 6
Javascript Question

Trigger focus on an element at a given position

I come to you with an intersting question.

Given position (x,y) in an HTML document, how can you trigger a focus event on an element at that given position.

The problem translates into is there any way to select the element matching a given position?

Sort of like getElementByPosition?

Answer

The easiest option is to use elementFromPoint:

var element = document.elementFromPoint(x, y);
element.focus();

Other than that, you can write your own function. This is what first came to mind - I used it a while back when there was some reason for elementFromPoint not working correctly, I don't remember what exactly. There are likely to be better ways to do it, but I just tried what I thought of first:

var coords = [100, 100],
    elems = document.getElementsByTagName("*");
for(var i = 0; i < elems.length; i++) {
    var left = elems[i].offsetLeft,
        top = elems[i].offsetTop,
        width = elems[i].offsetWidth;
        height = elems[i].offsetHeight;
    if((left <= coords[0]) && (left + width >= coords[0]) && (top <=coords[1]) && (top + height >= coords[1])) {
        elems[i].focus();
    }
}

You can see it working here.