How to detect scroll to bottom of html element
I think that all you want to do is detect the position of scroll.
@HostListener("window:scroll", ["$event"])
onWindowScroll() {
//In chrome and some browser scroll is given to body tag
let pos = (document.documentElement.scrollTop || document.body.scrollTop) + document.documentElement.offsetHeight;
let max = document.documentElement.scrollHeight;
// pos/max will give you the distance between scroll bottom and and bottom of screen in percentage.
if(pos == max ) {
//Do your action here
}
}
Also don't forget to import HostListener from @angular/core.
Detect bottom scroll
You can use the ionScroll
events here
since there is no scrollBottom
(which is a counterpart for `scrollTop), you need to get it yourself. So here:
In your .html
, add (ionScroll)
to handle any scroll events
<ion-content (ionScroll)="detectBottom()">
....
</ion-content>
And in your .ts
//make sure you import the correct modules
@ViewChild(Content) content: Content;
...
detectBottom(){
if(this.content.scrollTop == this.content.scrollHeight - this.content.contentHeight){
console.log("bottom was reached!");
}
}
Scroll events happen outside of Angular's Zones. This is for
performance reasons. So if you're trying to bind a value to any scroll
event, it will need to be wrapped in azone.run()
Please refer to this example on stackblitz
Check if user has scrolled to the bottom in Angular 2
// You can use this.
@HostListener("window:scroll", [])
onScroll(): void {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
}
Tracking scroll position and notifying other components about it
I think the easiest way is each interested component listening to the scroll event.
@Component({
...
// alternative to `@HostListener(...)`
// host: {'(window:scroll)': 'doSomething($event)'}
})
class SomeComponent {
@HostListener('window:scroll', ['$event'])
doSomething(event) {
// console.debug("Scroll Event", document.body.scrollTop);
// see András Szepesházi's comment below
console.debug("Scroll Event", window.pageYOffset );
}
}
plunker
Plunker using @HostListener()
Hint:
bootstrap(MyComponent, [
provide(PLATFORM_DIRECTIVES, {useValue: [TrackScrollDirective], multi:true})]);
makes the directive universal without adding it to every components directive: [...]
list.
How to detect scroll reached end in ion-content component of Ionic 4?
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:
Detect scroll event on element.nativeElement angular
The actual scroll code is fine. The reason it's not working in the Angular 8 version is that you're scrolling on the page, not on the div
. The difference between the two is that the working example has a fixed height with overflow: scroll
whereas the non-working example has the div
taking up its entire height.
To get it to work, you can simply add the following css to the .scrolling-guy
div:
height: 500px;
overflow-y: scroll;
Working example
Related Topics
Error Error: Formcontrolname Must Be Used With a Parent Formgroup Directive
Select Country Dropdown in HTML Page
React: Action on Variable Change
Rendering HTML Content With @Html.Raw in Razor Mail Template
Why Is There a White Space Between Parent Div and Inner Div in React
When Flexbox Items Wrap in Column Mode, Container Does Not Grow Its Width
Expand a Div to Fill the Remaining Width
Difference Between Localstorage, Sessionstorage, Session and Cookies
Applying a Background to ≪Html≫ And/Or ≪Body≫
Call Method from HTML Only One Time in Angular2
How to Prevent Flex-Items from Overflowing Flex Parent With No Wrap
Item Moving Around When Window Resized
Html Wont Link to CSS File in Visual Studio Code
100Vh Height When Address Bar Is Shown - Chrome Mobile
Make a Div Fill the Height of the Remaining Screen Space
Can Multiple Different HTML Elements Have the Same Id If They'Re Different Elements