1

I have a sticky navigation bar and I want to click on a button and get that element to be scrolled into view.

This works however it always puts the header on top of the element I am trying to scroll into view.

html template:

<div id="arrow-wrapper">      
                <div (click)="onArrowClick()" class="arrow-border">        
                  <div class="arrow down"></div>
                   <div class="pulse"></div>               
                </div>    
              </div>  
...
<div style="padding: 0 10px;">
  <h1 #gearUp [ngClass]="routeAnimationsElements" class="heading">Gear Up!</h1>

Component.ts file:

@ViewChild('gearUp') merchandiseCards: ElementRef;

onArrowClick(){
    const targetELement = this.merchandiseCards.nativeElement as HTMLElement;    
    //targetELement.scrollIntoView({behavior: 'smooth'});
    const elementPosition = targetELement.getBoundingClientRect().top;
    const offsetPosition = elementPosition - 50;
    window.scrollTo({
      top: offsetPosition,
      behavior: 'smooth'
    })
    targetELement.scrollBy({
      top: offsetPosition,
      behavior: 'smooth'
    })
  }

In the above example the window.scrollTo or targetElement.scrollBy do not work. Only targetElement.ScrollIntoView works but this puts the header element over top of the anchor element. How should I approach this?

O.MeeKoh
  • 1,976
  • 3
  • 24
  • 53
  • Have you tried messing around with the z-index of the element you want to see appear on top? – Vincent Gagnon Apr 30 '19 at 11:35
  • I have not, but mainly because I do not want to display the anchor element on top of the header. I want to be displayed below the header as if the header were part of the normal document flow. – O.MeeKoh Apr 30 '19 at 11:36
  • maybe this helps : https://stackoverflow.com/questions/46658522/how-to-smooth-scroll-to-page-anchor-in-angular-4-without-plugins-properly/51400379#51400379 – Joel Joseph Apr 30 '19 at 11:39
  • also read this : http://joeljoseph.net/angular-sticky-header-on-scroll/ – Joel Joseph Apr 30 '19 at 11:40
  • this does work and in fact it works as expected, but it does not account for the sticky header. – O.MeeKoh Apr 30 '19 at 11:40

1 Answers1

2

Well not too sure whether it's actually a good idea to access a different elem by using document.getElemBy... (for refactorings etc.), but you could do something like this:

const navigationRect = document.getElementById('sticky-header-id').getBoundingClientRect();
const padding = 30; // if needed
const offSet = navigationRect.top + navigationRect.height + padding;

const currElemRect = this.el.nativeElement.getBoundingClientRect();

const currentElemPosition = window.scrollY + currElemRect.top;
const scrollY = currentElemPosition - offSet;
window.scrollTo(0, scrollY);
Erbsenkoenig
  • 1,584
  • 14
  • 18