JSFiddle - React, Tailwind, and code Playground

by tuanderful

HTML

<h3>
Example of Chrome IntersectionObserver implementation
</h3>
<p><em>Example only works in Chrome</em></p>
<p>Expected behavior: the callback should be called when the item scrolls in and out of view (when the threshold crosses 0).</p>
<p><em>Please see <a href="https://jsfiddle.net/tuanderful/sjyu79vc/6/" target="_blank">https://jsfiddle.net/tuanderful/sjyu79vc/6/</a> for an example of polyfill behavior.</em></p>

<div id="grid">
  <div id="item1" class="gridItem" style="top: 0; left: 0">
  </div>
  <div id="item2" class="gridItem" style="top: 2000px; left: 0">
  </div>
</div>

CSS

body {
  height: 100%;
  overflow-y: scroll;
}

#grid {
  position: relative;
}

.gridItem {
  width: 200px;
  height: 300px;
  background: rgba(0, 0, 204, .6);
  position: absolute;
}

JavaScript

// Create IntersectionObserver, observe the grid items
var options = {
    rootMargin: '0px',
    threshold: 0
};

var callback = (entries, observer) => {
    console.log('Callback is called');
    entries.forEach((entry) => {
        console.log(entry);
    })
};

var observer = new IntersectionObserver(callback, options);
observer.observe(document.querySelector('#item1'));
observer.observe(document.querySelector('#item2'));