Pavel Sherin
Pavel Sherin

Reputation: 41

Angular 4 Scroll Element Offset Top Value

In jQuery element.offset().top gives on fixed element current position from the document top. When I'm scrolling down it grows up when scrolling up the offset top value decreses.

Now I need the same behavior in Angular 4, but I'm something missing, my offset top value is still the same.

Please see the attached Plunker: https://embed.plnkr.co/3sDzpRcJMEN6lndw4MUB

 @Component({
  selector: '[my-app]',
  template: `
    <div>
      <h2>There is document top</h2>
      <div class="fixed-box" #fixedBox>
        <p>I'm fixed box</p>
        <p>I wanna know my offset from the document top (not viewport) in every scroll step</p>
        <p>My current position from the document top is: {{ fixedBoxOffsetTop }}px</p>
        <p>My current position from the document top is: {{ fixedBoxOffsetTopOtherMethod }}px</p>
      </div>
    </div>
  `,
})
export class App implements OnInit {
  fixedBoxOffsetTop: number  = 0;
  fixedBoxOffsetTopOtherMethod: number = 0;

  @ViewChild('fixedBox') fixedBox: ElementRef;

  constructor() {}

  ngOnInit() {}

  @HostListener("window:scroll", [])
  onWindowScroll() {
    this.fixedBoxOffsetTop = this.fixedBox.nativeElement.offsetTop; // This value looks like init value and doesn't change during scroll
    this.fixedBoxOffsetTopOtherMethod = this.fixedBox.nativeElement.getBoundingClientRect().top; // The same result as offsetTop
  }
}

Can anybody help?

Upvotes: 4

Views: 21184

Answers (2)

Pavel Sherin
Pavel Sherin

Reputation: 41

There is my method for that:

getCurrentOffsetTop(element: ElementRef) {
  const rect = element.nativeElement.getBoundingClientRect();
  return rect.top + window.pageYOffset - document.documentElement.clientTop;
}

Upvotes: -1

yurzui
yurzui

Reputation: 214017

You missed window and document offsets:

const rect = this.fixedBox.nativeElement.getBoundingClientRect();
this.fixedBoxOffsetTop = rect.top + window.pageYOffset - document.documentElement.clientTop;

Forked Plunker

Upvotes: 7

Related Questions