bhansa
bhansa

Reputation: 7514

Not able to get correct position of element when clicking via tab key

I am getting the correct position of the element if I click using mouse, but not able to get if click through tab key.

To reproduce the behavior, focus on the element using tab and press Enter.

var linkElement = document.getElementById('link');
linkElement.addEventListener('click', function(e){
  console.log(e.clientX, e.clientY);
});
#link{
  position: absolute;
  top: 5%;
  left: 15%;
}
#placeholder{
  display: none;
  background: rgba(0, 0, 0, 0.4);
}
<a href="javascript:void(0)" id="link">
LINK
</a>

<div id="placeholder">
  PLACEHOLDER
</div>

Upvotes: 2

Views: 91

Answers (1)

jeprubio
jeprubio

Reputation: 18012

It seems that clientX and clientY is only for the mouse according to this.

What I would do is to return the coords of the center on tab by the offset properties (when the clientX and the clientY are 0,0):

var linkElement = document.getElementById('link');
linkElement.addEventListener('click', function(e){
  if (e.clientX > 0 && e.clientY > 0) {
      console.log(e.clientX, e.clientY);
  } else {
      console.log(this.offsetLeft + (this.offsetWidth / 2), this.offsetTop + (this.offsetHeight / 2));
  }
});
#link{
  position: absolute;
  top: 5%;
  left: 15%;
}
#placeholder{
  display: none;
  background: rgba(0, 0, 0, 0.4);
}
<a href="javascript:void(0)" id="link">
LINK
</a>

<div id="placeholder">
  PLACEHOLDER
</div>

UPDATE:

Or with getBoundingRect as epascarello suggested:

var linkElement = document.getElementById('link');
linkElement.addEventListener('click', function(e){
  if (e.clientX > 0 && e.clientY > 0) {
      console.log(e.clientX, e.clientY);
  } else {
      var boundingRect = this.getBoundingClientRect();
      console.log(Math.round(boundingRect.x + (boundingRect.width / 2)), Math.round(boundingRect.y + (boundingRect.height / 2)));
  }
});
#link{
  position: absolute;
  top: 5%;
  left: 15%;
}
#placeholder{
  display: none;
  background: rgba(0, 0, 0, 0.4);
}
<a href="javascript:void(0)" id="link">
LINK
</a>

<div id="placeholder">
  PLACEHOLDER
</div>

Upvotes: 1

Related Questions