IntersectionObverser Sample

HTML

<h1>test</h1>
<div>xxx</div>
<div>xxx</div>
<div>xxx</div>
<div>xxx</div>
<div id="target">zzz</div>
<div>xxx</div>

CSS

h1 {
  position: fixed;
}
div {
  height: 200px;
}

JavaScript

const h1 = document.querySelector('h1');
const el = document.querySelector('#target');
const color = '#aaa';
el.style.backgroundColor = color;

var io = new IntersectionObserver(
	entries => {
  console.log(entries);
  	const ratio = entries[0].intersectionRatio;
    console.log(entries.length, ':', ratio);
		entries[0].target.style.backgroundColor = color;
  	if (ratio > 0) {
    	h1.textContent = 'visible';
      if (ratio >= 0.5) {
      	entries[0].target.style.backgroundColor = 'red';
      }
    } else {
    	h1.textContent = 'hidden';
    }
	},
  {
  	threshold: [0, 0.5]
  }
);
io.observe(el);