Reputation: 2136
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?
Upvotes: 1
Views: 950
Reputation: 1659
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);
Upvotes: 2