Scroll to top in ionic

#1

How do we trigger to scroll to top in ionic 2? ionic 1 had some delegates to do this, but not sure how i can do this in ionic 2. Some use case might be

  • If sidemenu has a long list of menus, and if one touches the menu than scroll to the top of the list in sidemenu.

Also would love to know how to scroll to specific element in ionic 2 as well.

Ion Slides not starting at the top of slide
#2

In this case, you can use the .scrollToTop() method on the content class.

3 Likes
#3

awesome. thanks. was the element I should look for :slight_smile: nice.

#4

hi @mhartington, the scrollToTop in the attached code, is not working for me. please advise.

in html file:

<ion-content id="listScroll">
 <ion-list [style.direction]="direction" >   
     <ion-item  *ngFor="let item of selectedEntItems | objToIterable;let ind=index" >
         <!--List item header-->
         <!--List item content-->
    </ion-item>    
 </ion-list>
 <ion-infinite-scroll *ngIf="loadMoreData()==true" (ionInfinite)="doInfinite($event)"> 
 </ion-infinite-scroll>
</ion-content>

in ts file:

let scrollContent: Content = document.getElementById(“listScroll”);
scrollContent.scrollToTop;

#5

is it possible to only scrollToTop when a tab is changed, i tried doing it in the components viewDidload but that occurs everytime a page is in view coming back to the page from a sub-page, for example users list, item clicked, go back to users list and the scrollToTop will occur.

#6

Did you try putting parentheses after scrollToTop?

  scrollContent.scrollToTop();

Otherwise Javascript may simply do nothing at that line, and not give you an error.

#7

In your .html file

<ion-content #pageTop>
  <!-- Other content here -->
</ion-content>

In your .ts file

import { Content } from 'ionic-angular';

//
//...
//

export class ScrollPage{
  @ViewChild('pageTop') pageTop: Content;

  /**
   * Method to scroll to top
   */
  public pageScroller(){
    //scroll to page top
    this.pageTop.scrollToTop();
  }
}
6 Likes
#8

for ionic 4 you can use this code

import { Component, ViewChild } from '@angular/core';
import { IonContent } from '@ionic/angular';

@Component({...})
export class MyPage{
  @ViewChild(IonContent) content: IonContent;

  scrollToTop() {
    this.content.scrollToTop(400);
  }
  ionViewDidEnter(){
    this.scrollToTop();
  }
}
#9

For Ionic’s 4.x we can implement ScrollToTop as explained here