Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 4 smooth scroll to anchor

I've got a single landing page with a menu and some sections. Each item in the menu should scroll smoothly to the given section.

My first approach was to do:

window.scrollTo({
  y: this.el.nativeElement.querySelector('app-contact').offsetTop // 600
  behavior: 'smooth'
});

The problem I was facing:

  1. Ionic 4 doesn't seem to respond to scrollTo Even if I write window.scrollTo(0, 300), nothing will happen.

  2. behavior: 'smooth' is not supported in every browser. Therefore, I can't use this approach.

I was wondering how should I implement a smooth scroll to an anchor using Ionic 4.

like image 300
Eliya Cohen Avatar asked Jun 28 '26 04:06

Eliya Cohen


1 Answers

Ionic handles scrolling in it's ion-content component.

The content component comes with a few scroll methods like scrollToPoint which might be usefull to you.

To get an IonContent object you need to use ViewChild

import {ViewChild} from '@angular/core'
export class yourPage {
  @ViewChild('ion-content') content: IonContent;
  scroll(x, y) {
    this.content.scrollToPoint(x, y, 300)
  }
}

Or alternatively scrollByPoint if you want to scroll a certain distance

like image 104
Dwagh Avatar answered Jun 29 '26 21:06

Dwagh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!