I've developed a scroll-to-top feature for my Angular project, but I'm facing an issue. The scroll icon appears immediately upon page load instead of only showing after the user scrolls down. Any ideas or suggestions on how to achieve this?
Here's what I'm aiming for:
- Hide the scroll icon when the page loads
- Show the scroll icon only when the user scrolls down
HTML
<div class="to-top" (click)="scrollToTop()" [ngClass]="{ 'show-scrollTop': windowScrolled }">
<img src="../../../../assets/marketing-site/ecosystem/Scroll-to-Top.svg" alt="to-top-icon" />
</div>
CSS
.to-top {
bottom: 0;
cursor: pointer;
margin: 0 8px 12px 0;
position: fixed;
right: 0;
}
.show-scrollTop {
opacity: 1;
transition: all 0.2s ease-in-out;
}
TS
scrollToTop(): void {
// scroll to the top of the body
return this.document.body.scrollIntoView({
behavior: 'smooth',
block: 'start',
inline: 'start',
});
}
Check out the example I created here