Here are the steps to get this functionality working:
- Create a function that will scroll your
scroll-content
element to the top
- Monitor and keep track of the scroll position of your
scroll-content
- Utilize
*ngIf
on your scroll-to-top button to show it only when the scroll-content
has scrolled past a certain threshold.
Function to Scroll to Top
I modified this Stack Overflow answer to suit the scroll-content
element
scrollToTop(scrollDuration) {
let scrollStep = -this.ionScroll.scrollTop / (scrollDuration / 15);
let scrollInterval = setInterval( () => {
if ( this.ionScroll.scrollTop != 0 ) {
this.ionScroll.scrollTop = this.ionScroll.scrollTop + scrollStep;
} else {
clearInterval(scrollInterval);
}
}, 15);
Tracking scroll-content
Position
In this example, we use the window height as the benchmark for showing the scroll-to-top button:
this.ionScroll.addEventListener("scroll", () => {
if (this.ionScroll.scrollTop > window.innerHeight) {
this.showButton = true;
} else {
this.showButton = false;
}
});
Button HTML Code
<button *ngIf="showButton" (click)="scrollToTop(1000)">Go to Top</button>
Complete TypeScript Component Code
import { NavController } from 'ionic-angular/index';
import { Component, OnInit, ElementRef } from "@angular/core";
@Component({
templateUrl:"home.html"
})
export class HomePage implements OnInit {
public ionScroll;
public showButton = false;
public contentData = [];
constructor(public myElement: ElementRef) {}
ngOnInit() {
// Reference Ionic scroll element
this.ionScroll = this.myElement.nativeElement.children[1].firstChild;
// Function triggered on scroll event
this.ionScroll.addEventListener("scroll", () => {
if (this.ionScroll.scrollTop > window.innerHeight) {
this.showButton = true;
} else {
this.showButton = false;
}
});
// Populate content data
for (let i = 0; i < 301; i++) {
this.contentData.push(i);
}
}
// Scroll to top function
// Modified from https://stackoverflow.com/a/24559613/5357459
scrollToTop(scrollDuration) {
let scrollStep = -this.ionScroll.scrollTop / (scrollDuration / 15);
let scrollInterval = setInterval( () => {
if ( this.ionScroll.scrollTop != 0 ) {
this.ionScroll.scrollTop = this.ionScroll.scrollTop + scrollStep;
} else {
clearInterval(scrollInterval);
}
}, 15);
}
}
Entire Component HTML Structure
<ion-navbar primary *navbar>
<ion-title>
Ionic Framework Example
</ion-title>
<button *ngIf="showButton" (click)="scrollToTop(1000)">Go to Top</button>
</ion-navbar>
<ion-content class="has-header" #testElement>
<div padding style="text-align: center;">
<h1>Testing Ionic Framework</h1>
<div *ngFor="let item of contentData">
Test content-{{item}}
</div>
</div>
</ion-content>