0

I am using the Intersection Observer API to help me with a parallax effect. So far everything work well except for one scenario:

When the image is already visible and in the middle of the page, as long as the image it not intersecting with the edge of the viewport, there is not callback trigger. So no way for me to update the position of the parallax translation with the boundingClientRect received from the callback.

    buildThresholdList(element) {
        let thresholds = [];
        let elementHeight = element.getBoundingClientRect().height;
        for (var i=1.0; i<=elementHeight; i++) {
            var ratio = i/elementHeight;
            thresholds.push(ratio);
        }

        return thresholds;
    }

    createIntersectionObserver(element) {
        const options = {
            root: null,
            threshold: this.buildThresholdList(element),
        }
        this.observer = new IntersectionObserver(this.intersectionObserverCallback, options);
    }

    intersectionObserverCallback(entries) {
        entries.forEach(entry => {
            let target = entry.target;

            if (entry.isIntersecting) {
                //calculate the translated value
                this.getTranslateValue(entry);
            }
         }
    }

Is there a way with the Intersection Observer API to have a callback even though the image is fully visible and not intersecting with anything?

user3415011
  • 195
  • 1
  • 2
  • 11
  • Would like to see the rest of the code, because I'm searching for a solution to build a parallax effect with the intersection observer. Did you get it to work and may you share the whole solution? – Malte Jul 27 '21 at 20:40

1 Answers1

0

A quick workaround for Chrome (since this seems to be a Chrome-specific issue) is to trigger layout calculation while the animation is happening. Adding something like this seems to work, but you would probably want to add some transitionstart/transitionend events to ensure it's only running when transition is active.

  const refresh = () => {
    image.clientWidth // triggers layout, which triggers intersection to be recalculated
    requestAnimationFrame(refresh)
  }
  requestAnimationFrame(refresh)

Demo: https://jsfiddle.net/01qa26L5/

Andrej Pavlovic
  • 364
  • 4
  • 12