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?

5
  • Have you tried messing around with the z-index of the element you want to see appear on top? Commented Apr 30, 2019 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. Commented Apr 30, 2019 at 11:36
  • maybe this helps : stackoverflow.com/questions/46658522/… Commented Apr 30, 2019 at 11:39
  • also read this : joeljoseph.net/angular-sticky-header-on-scroll Commented Apr 30, 2019 at 11:40
  • this does work and in fact it works as expected, but it does not account for the sticky header. Commented Apr 30, 2019 at 11:40

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.