1

I am trying to determine whether a slot element has a scrollbar. If it does I want to add a show all/show fewer link next to the slot which will expand or contract it accordingly.

I am using IntersectionObserver because it seems designed for this very use case. The slot contains a ul which itself has a variable number of li children. The ul is not populated until after the function that adds the show more/show link is fired - hence the use of IntersectionObserver. The function I wrote should return a boolean:

_isOverflowing( rootElem, childElem ) {
    // rootElem is the slot; childElem is the ul
    let observer;

    const options = {
        root: rootElem,
        threshold: 1.0
    };

    function handleIntersect(entries, observer) {
        entries.forEach(entry => {
            return entry.intersectionRatio >= options.threshold
        });
    }

    observer = new IntersectionObserver(handleIntersect, options);
    return observer.observe( childElem );
}

What I am seeing is that the final function

observer.observe( childElem )

returns as undefined. What am I doing wrong?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
dylanmac
  • 353
  • 1
  • 7
  • 19
  • 1
    It's async, there's nothing to return. That's why you pass a callback to the constructor. – Jared Smith May 25 '18 at 19:51
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jared Smith May 25 '18 at 19:53
  • Possible duplicate of [What does \`return\` keyword mean inside \`forEach\` function?](https://stackoverflow.com/questions/34653612/what-does-return-keyword-mean-inside-foreach-function) – Sebastian Simon May 25 '18 at 20:12
  • I see. So i have to put all operations in the callback function, e.g. showing/hiding DOM elements. I tried that and it works. Thanks. – dylanmac May 25 '18 at 22:47

0 Answers0