To do this, you need to:
- Create a function that scrolls the
scroll-content element to the beginning - Track scroll position
scroll-content - Use
*ngIf on your scroll button upwards to conditionally show that after scroll-content reached a certain threshold.
Go to the top function
I adapted this SO answer to apply to 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);
Track scroll-content position
This example uses window height as a threshold to show scrolling to the top button, for example:
this.ionScroll.addEventListener("scroll", () => { if (this.ionScroll.scrollTop > window.innerHeight) { this.showButton = true; } else { this.showButton = false; } });
Html button
<button *ngIf="showButton" (click)="scrollToTop(1000)">Scroll Top</button>
Full Typescript Component
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() { // Ionic scroll element this.ionScroll = this.myElement.nativeElement.children[1].firstChild; // On scroll function this.ionScroll.addEventListener("scroll", () => { if (this.ionScroll.scrollTop > window.innerHeight) { this.showButton = true; } else { this.showButton = false; } }); // Content data for (let i = 0; i < 301; i++) { this.contentData.push(i); } } // Scroll to top function // Adapted from /questions/2392/scrolltop-animation-without-jquery/25616
Full Html Component
<ion-navbar primary *navbar> <ion-title> Ionic 2 </ion-title> <button *ngIf="showButton" (click)="scrollToTop(1000)">Scroll Top</button> </ion-navbar> <ion-content class="has-header" #testElement> <div padding style="text-align: center;"> <h1>Ionic 2 Test</h1> <div *ngFor="let item of contentData"> test content-{{item}} </div> </div> </ion-content>
source share