1

I want to scroll to the Y and X center of my element when a certain function is fired. My HTML look like this (i want to scroll to the middle of #viewport):

 </div>
      <div #viewport class="document-view-port">
          <div #viewBox></div>
 </div>

Inside my TS i am importing the elements like this(here i try to find the y center):

  @ViewChild('viewBox') viewBox: ElementRef;
  @ViewChild('viewport') viewport: ElementRef; 

The last methods that i try to extract this center point to scroll is:

  zoomIn() {
    const elementRect = this.viewport.nativeElement.getBoundingClientRect();
    const absoluteElementTop = elementRect.top + window.pageYOffset;
    const middle = absoluteElementTop - (elementRect.height / 2);  
    this.viewport.nativeElement.scrollTo(0, middle)
  }

I just can't make it happen, any help would be appreciated

[edit]

The method scrollIntoView() don't do anything in my code. I want to find those cordinates and scroll without using any predefined function

Igor.ro
  • 37
  • 2
  • 9

1 Answers1

0

You should use window.scrollTo(x, y) for achieving the scroll:

zoomIn() {
    const elementRect = this.viewport.nativeElement.getBoundingClientRect();
    const absoluteElementTop = elementRect.top + window.pageYOffset;
    const middle = absoluteElementTop - (elementRect.height / 2);  
    window.scrollTo(0, middle); // have a window object reference in your component
  }
nircraft
  • 8,242
  • 5
  • 30
  • 46
  • Thanks for your help, i tried the code and its not doing anything `middle = -225` – Igor.ro May 07 '19 at 15:41
  • @Igor.ro what did you expect with -225? That is never going to work. Try debugging why its a negative value. The value must be positive to work. – enf0rcer May 07 '19 at 16:29