Seeking a more efficient way to display a button only on up-scroll. My current implementation involves listening for every scroll-event, which seems like it might be too computationally intensive. If anyone has a better approach, I'm open to suggestions! The Requirement is: When the Page initially loads or on up-scroll the button should be displayed in the UI. On down-scroll the button should be hidden.
I utilized Angular's @HostListener(..)
to monitor the scroll event.
Component
public lastScrolledHeight: number = 0;
public showAddButton: boolean = true;
@HostListener('window:scroll', ['$event']) onScroll(event) {
const window = event.path[1];
const currentScrollHeight = window.scrollY;
console.log(currentScrollHeight);
if (currentScrollHeight > this.lastScrolledHeight) {
this.showAddButton = false;
console.log('should NOT show button');
} else {
this.showAddButton = true;
console.log('should show button');
}
this.lastScrolledHeight = currentScrollHeight;
}
HTML
<button class="btn btn-success btn-circle btn-xl"
[ngClass]="(showAddButton === true) ? 'scale-in' : 'scale-out'"
</button>
Providing the CSS for completeness:
.scale-out {
-webkit-animation: scale-out .2s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
animation: scale-out .2s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
}
.scale-in {
-webkit-animation: scale-in .2s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
animation: scale-in .2s cubic-bezier(0.550, 0.085, 0.680, 0.530) both;
}
Open to any feedback. :)