Trigger focus on an element in a given position

I come to you with a question.

The specified position (x, y) in the HTML document, how you can trigger a focus event for an element at that given position.

The problem is, is there a way to select an item that matches this position?

Like like getElementByPosition?

+4
source share
2 answers

The easiest option is to use elementFromPoint :

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

In addition, you can write your own function. This is what first occurred to me - I used it some time ago, 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 this, but I just tried what I was thinking before:

 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 how it works here .

+4
source
+1
source

All Articles