Get element "global" coordinates

53 Views Asked by At

I'm writing a chrome extension to change how keyboard navigation works. Basically I'm using w,a,s,d keys to navigate trough buttons, links, input fields, etc. My problem begins when I have to get the element "coordinates", I'm using element.getBoundingClientRect(); for this and using element.offsetWidth and element.offsetHeight to get the element corners.

I was testing my extension on stackoverflow homepage. The top-left element of the page is selected and using the keybinding i could navigate trough the header. My problem is that instead of going to the right element, the extension jumped to the searchbar. When looking into the logs, i was able to see the element corners.

enter image description here

the previous element is the menu button and the element in question is the searchbar. The corners look so off, in the page, they are quite at the same level, but when I get the corners, it goes completely off.

Is there a way to get the abosolute coordinates of an element?

This is my function to get the right element:

function getRightItem(){
  
  xDiff = Infinity;
  yDiff = Infinity;

  let iterationElement = null;
  
  let myBottom = focusedElementPosition.y + focusedElement.offsetHeight;
  let myRight = focusedElementPosition.x + focusedElement.offsetWidth;
  let myLeft = focusedElementPosition.x;
  let myTop = focusedElementPosition.y;

  console.log("previous element", {"bottom": myBottom,"right": myRight,"left": myLeft,"top": myTop});
  
  for (const [mapKey, innerMap] of clickable.entries()) {
    if (innerMap.size > 0) {
      for (const [element, position] of innerMap.entries()) {
        var bottom = position.y + element.offsetHeight;
        var right = position.x + element.offsetWidth;
        var left = position.x;
        var top = position.y;
        
        if(left < xDiff && left > myRight){
          if(top < yDiff){
            xDiff = left;
            yDiff = top;
            iterationElement = [element, position];
          }
        }
      }
    }
  }
  focusedElement.style.border = "";
  console.log("element in question", {"bottom": bottom,"right": right,"left": left,"top": top});
  
  setNewElement(iterationElement);
}

In case anyone needs, here it goes my setNewElement() function

function setNewElement(element){
  focusedElement = element[0];
  focusedElementPosition = {"x":element[1].x, "y":element[1].y};
  focusedElement.focus();
}

I tried using the css position values (right, top, left, bottom) thinking it would grab the absolute coordinates but it turned out not all elements have those defined

0

There are 0 best solutions below