angularmouseeventbrave

mousemove event not return the correct mouse position


I try to put a tooltip that follow mouse position with the next code:

  @HostListener('mousemove', ['$event']) onMouseMove(event) {
    let tooltipNode = document.getElementsByClassName('dhemax-tooltip')[0] as HTMLElement;
    tooltipNode.style.left = event.pageX + 'px'
    tooltipNode.style.top = event.pageY + 'px';
  }

  public onMouseOver (event) {
    let tooltipNode = document.getElementsByClassName('dhemax-tooltip')[0] as HTMLElement;
    tooltipNode.style.display = 'block';
    this.tooltipMsg = event.target.innerText;
  }

  public onMouseOut (event) {
    let tooltipNode = document.getElementsByClassName('dhemax-tooltip')[0] as HTMLElement;
    tooltipNode.style.display = 'none';
  }

And this is the css for my tooltip:

.dhemax-tooltip {
  z-index: 999;
  display: none;
  position: absolute;
  background: #FFFFFF;
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25);
  padding: 8px;
  font-family: 'Nunito';
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 100%;
  letter-spacing: 0.01em;
  color: #828282;
}

My tooltip is just a div:

<div class="dhemax-tooltip"> {{ tooltipMsg }} </div>

This is the result:

enter image description here

(I put a red circle in mouse position, the tooltip is too far from the current mouse position)


Solution

  • This is not an Angular issue, but a CSS one. The positioning of the element in question is set to absolute, which means it's positioned relative to a parent container with position:relative.

    In your case, you want to position relative to the page/viewport, so you need to change it to position:fixed. See also this explanation about CSS Layout.