Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect scroll to bottom of html element

I have this element that I'm referencing by Id:

    let infiniteScrollElement = document.getElementById('th-infinite-scroll-tracker');

I need to listen when the browser is has reached the bottom of the element.

How to achieve this?

like image 571
CommonSenseCode Avatar asked Nov 17 '16 20:11

CommonSenseCode


People also ask

How do I check if a div is scrolled to the bottom?

To detect when a user scrolls to bottom of div with React, we can check if the sum of the scrollTop and clientHeight properties of a scrollable element is equal to the scrollHeight property of the same element. We call the useRef hook to create a ref and we assign the returned ref to the inner div, which is scrollable.

How do I auto scroll to the bottom in HTML?

To auto scroll a page from top to bottom we can use scrollTop() and height() method in jquery. In this method pass the document's height in scrollTop method to scroll.


3 Answers

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.

like image 22
YASH DAVE Avatar answered Oct 14 '22 15:10

YASH DAVE


You could check whether the user has scrolled to the bottom or not in the below way...

Html file

<div (scroll)="onScroll($event)">
    ...
    ...
</div>

typescript file

onScroll(event: any) {
    // visible height + pixel scrolled >= total height 
    if (event.target.offsetHeight + event.target.scrollTop >= event.target.scrollHeight) {
      console.log("End");
    }
}
like image 188
Narottam Goyal Avatar answered Oct 14 '22 16:10

Narottam Goyal


You could do this with an observable that's tracking the scroll event of your container.

Or you could create a host listener for your component that's listening for the scroll event. Please have a look at this SO question. (I haven't tested it with a host listener but that should work.)

Add the following code to your component for observable approach (I've copied some of the code from this blog post. ):

  ngOnInit() {
    /*
     * Create the observable from an event, in this case, the window scroll event
     * then map each event so we can get a new value from it
     * i.e. over time, we are just dealing with a collection:
     * (map [e1, e2, e3, ...]) -> [t1, t2, t3, ...]
     */
    let tracker = document.getElementById('th-infinite-scroll-tracker');

    let windowYOffsetObservable = Observable.fromEvent(tracker, 'scroll').map(() => {
      // I don't actually care about the event, I just need to get the window offset (scroll position)
      return tracker.scrollTop;
    });

    // subscribe to our Observable so that for each new item, our callback runs
    // this is our event handler
    let scrollSubscription = windowYOffsetObservable.subscribe((scrollPos) => {
      let limit = tracker.scrollHeight - tracker.clientHeight;
      console.log(scrollPos, limit);
      if (scrollPos === limit) {
        alert('end reached');
      }
    });
  }

Update

Another way and probably the best would be to create a directive for your tracking logic. Then you can easily use HostListener to bind to the scroll event.

Typescript code:

import {
  Directive, HostListener
}
from '@angular/core';

@Directive({
  selector: '[scrollTracker]'
})
export class ScrollTrackerDirective {
  @HostListener('scroll', ['$event']);

  onScroll(event) {
    // do tracking
    // console.log('scrolled', event.target.scrollTop);
    // Listen to click events in the component
    let tracker = event.target;

    let limit = tracker.scrollHeight - tracker.clientHeight;
    console.log(event.target.scrollTop, limit);
    if (event.target.scrollTop === limit) {
      alert('end reached');
    }
  }

  constructor() {}
}

Markup in your component (add your directive)

<div id="th-infinite-scroll-tracker" style="overflow-y:scroll; height: 500px;" scrollTracker>
  .... your container with scrollbar ...
</div>
like image 35
AWolf Avatar answered Oct 14 '22 16:10

AWolf