5

I'm trying to do some UX updates to a component and I'd like to use the Intersection Observer functionality (https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) to show/hide a message when an html component is visible on the screen.

If I try and use the following I get an error "IntersectionObserver is not a constructor"

let observer = new IntersectionObserver(
  function(entries) {
    if (entries[0].isIntersecting === true) {
      console.log("Element is fully visible in screen");
    }
  },
  { threshold: [1] }
);

observer.observe(this.template.querySelector("#stop"));

I assume the LockerService is stopping access to the API -am I correct? If so, is there a way around this? Or is there a way to provide similar functionality? Have googled with no success...

This is in an LWC so cannot just change the API version to 39.0 as in the docs.

Many thanks in advance.

2

1 Answer 1

5

As stated, IntersectionObserver isn't supported, but that isn't the only way to accomplish this task.

You can simply add a scroll event listener to the window and do some maths to figure out if the element is in view

connectedCallback(){
        var self = this;
        window.addEventListener('scroll', event => {
            console.log(window.scrollY);
            var div = self.template.querySelector('div');
            if (div){
                var rect= div.getBoundingClientRect();
                // calculations here
                console.log(rect.y);
            }
        });
    }

All you need to do is take the window's scrollY and innerHeight values and compare to the bounding box y and height values to see if the element is within the current view!

Of course, you can also apply a scroll event to a scrollable item if you don't need the whole page.

Note, getBoundingClientRect() works a bit differently in IE, so you should read up on that here if you can't just force your users to use Chrome

1
  • Thanks @stackasaur I think that will work; I'll try it out when I get a chance. I'll mark as the correct answer in the meantime. Dec 2, 2020 at 16:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .