In Ionic v3 ion-content there was properties like "scrollTop". In Ionic v4 there are no more of this properties... How could I determine if a user reached the end of the content?
https://ionicframework.com/docs/v3/api/components/content/Content/ https://ionicframework.com/docs/api/content
These features are still available they are just in a different location.
After enabling it with scrollEvents
, you need to use the ionScroll
event and then calculate the height based on the results of the getScrollElement()
function, not the ion-content
- that has a fixed height of the window height.
I've written an example below. You can remove the console.log
's and tighten it up a bit, I just left them in to help you understand what's going on.
Example page:
<ion-header>
<ion-toolbar>
<ion-title>detectScrollToBottom</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [scrollEvents]="true" (ionScroll)="logScrolling($event)">
<p *ngFor="let dummy of ' '.repeat(75).split('')">Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia placeat nam sapiente iusto eligendi</p>
</ion-content>
Example code:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-detect-scroll-to-bottom',
templateUrl: './detect-scroll-to-bottom.page.html',
styleUrls: ['./detect-scroll-to-bottom.page.scss'],
})
export class DetectScrollToBottomPage implements OnInit {
private scrollDepthTriggered = false;
constructor() { }
ngOnInit() {
}
async logScrolling($event) {
// only send the event once
if(this.scrollDepthTriggered) {
return;
}
console.log($event);
if($event.target.localName != "ion-content") {
// not sure if this is required, just playing it safe
return;
}
const scrollElement = await $event.target.getScrollElement();
console.log({scrollElement});
// minus clientHeight because trigger is scrollTop
// otherwise you hit the bottom of the page before
// the top screen can get to 80% total document height
const scrollHeight = scrollElement.scrollHeight - scrollElement.clientHeight;
console.log({scrollHeight});
const currentScrollDepth = scrollElement.scrollTop;
console.log({currentScrollDepth});
const targetPercent = 80;
let triggerDepth = ((scrollHeight / 100) * targetPercent);
console.log({triggerDepth});
if(currentScrollDepth > triggerDepth) {
console.log(`Scrolled to ${targetPercent}%`);
// this ensures that the event only triggers once
this.scrollDepthTriggered = true;
// do your analytics tracking here
}
}
}
Example logs: