'intersectionObserver API: If the element is outside of the viewport

I wrote the bellow code which is adding some inline styling to an element once the element is out of the viewport.

const myDiv = document.querySelector('.my-div')

const obr = new IntersectionObserver(function(entries) {
    if (entries[0].intersectionRatio <= 0) {
    myDiv.style.top = '100px';
  }
});

obr.observe(myDiv);

The above code works fine.

But now I need to add the inline styling when only 100px of the element's height is still in the viewport. In other words the styling shouldn't get added once the element is entirely outside of the viewport but it should be added when most part of it is outside of the viewport and 100px of its height is still in the viewport.

How can I change the above code to achieve that? I think I need to set rootMargin to 100px, but not sure how to implement it into my code.

I tried this:

const observer = new IntersectionObserver({ rootMargin: '100px' }, entries => {...

But then I get the following error:

Uncaught TypeError: Failed to construct 'IntersectionObserver': parameter 1 is not of type 'Function'.


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source