Yogesh
Yogesh

Reputation: 286

Capture div id while using window:scroll

I have an angular 8 application and I am trying to using the window:scroll functionality to load a component when the scroll reaches that specific component. I can achieve this by using a window.pageYOffset but as the height of the component is a dynamic window.pageYOffset won't help. Is there a way to identify if the scroll has reached that component by identifying an id or something? Can I capture the id using the event?

This is what I tried:

@HostListener('window:scroll', ['$event']) onScroll(event) {
    if (window.pageYOffset >= 350) {
        this.scrollPointReached = true;
    }
}

Upvotes: 0

Views: 294

Answers (1)

cloned
cloned

Reputation: 6742

Don't use scroll event listener for this, use Intersection Observer (IO)

With this you can listen to whenever a container is getting visible in the viewport (or leaving the viewport and is no longer visible)

First, you create a new observer with your preferred options:

let options = {
  rootMargin: '0px',
  threshold: 1.0
}

let observer = new IntersectionObserver(callback, options);

Then you set the elements that need to be watched:

let singleTarget = document.querySelector('#observeTarget');
observer.observe(target);

let multiTargets = document.querySelectorAll('.targets');
multiTargets.forEach(target => observer.observe(target) )

Last you define what happens when the element comes into view:

let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.isIntersecting
    //   entry.rootBounds
  });
};

Here is a post on how to implement this with angular, just one of the many you can find.

Keep in mind that if you have to support IE you can't use this approach, then you will have to somehow implement your own logic using scroll events.

Upvotes: 1

Related Questions