Intersection Observer Test

by MegaScience

HTML

<div id="spook" class="centerText bottom">Spooky!<h1>AHHHH!</h1></div>

CSS

body {
  position: relative;
  height: 200vh;
  background-color: black;
  color: white;
}

#spook {
  border: 2px solid red;
  width: 100%;
}

#spook h1 {
  display: none;
}

#spook.intersecting h1 {
  display: block;
}

.centerText {
  text-align: center;
  justify-content: center;
  vertical-align: middle;
}

.bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 20vh;
}

JavaScript

// Help: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

function createObserver() {
  const observer = new IntersectionObserver(handleIntersect, { threshold: 0.75 })
  observer.observe(document.getElementById('spook'))
}

function handleIntersect(entries, observer) {
	for(const entry of entries)
		entry.target.classList.toggle('intersecting', entry.isIntersecting)
}

window.addEventListener('load', createObserver, false)