efarley
efarley

Reputation: 8661

Getting incorrect values for element's position from clientLeft, clientTop, offsetLeft, and offsetTop

I am trying to return the location of an element but for some reason the client, scroll and offset values for left and top are always wrong. The goal here is to determine if the user clicked outside of the dropdown element and if so close it so I need an accurate location for the element to compare against the click location.

For example I checked the location of the element using a ruler and it reads a left value of 1013px and a top value of 484px. However when I get the element in code and check offsetLeft the value is 3 and offsetTop is 16. What is going on here? It seems like I'm getting the location relative to the parent instead of the document.

I use angular and get the element using a template reference in the component.

dropdown.component.ts

@ViewChild('dropdown') dropdown: any; // Template reference to the element

constructor(
  private elementRef: ElementRef // Reference to the :host element
} { }

ngOnDestroy() {
  this.elementRef.nativeElement.removeEventListener('click', this.handleClick.bind(this));
}

ngOnInit() {
  this.subscribeToClickEvent();
}

private handleClick(event: MouseEvent): void {
  // this.dropdown.nativeElement.clientLeft equals 0
  // this.dropdown.nativeElement.clientTop equals 0
  // this.dropdown.nativeElement.offsetLeft equals 3
  // this.dropdown.nativeElement.offsetTop equals 16
  // this.dropdown.nativeElement.scrollLeft equals 0
  // this.dropdown.nativeElement.scrollTop equals 0
  // Left should equal ~1013 and top should equal ~484
}

private subscribeToClickEvent(): void {
  this.elementRef.nativeElement.addEventListener('click', this.handleClick.bind(this));
}

Upvotes: 2

Views: 3916

Answers (2)

Behemoth
Behemoth

Reputation: 9310

offsetLeft and offsetTop of an element return the offset relative to its offsetParent. This is either

  • a parent element with a non-static position
  • a td, th or table parent element (only if the element itself has position static)
  • or the document body.

Now depending on what you want, make sure to position your target element or its parent element accordingly.

Upvotes: 0

T4rk1n
T4rk1n

Reputation: 1460

You have to use the element.getBoundingClientRect() to get the accurate location.

Upvotes: 6

Related Questions