<header class="header">
	<nav>
		<a href="https://cydstumpel.nl/" target="_blank">
			Cyd Stumpel
		</a>
		<p>
			Interaction observer example
		</p>
	</nav>
</header>
<img src="https://pbs.twimg.com/media/BcvmxibIYAAH8a3.jpg" />
* {
	font-family: 'Helvetica Neue', Helvetica, sans-serif;
	margin: 0;
	box-sizing: border-box;
	color: inherit;
}

a {
	text-decoration: none;
}

.header {
	width: 100%;
	height: 5.75rem;
	&.background--dark nav {
		background: black;
		color: white;
	}
	nav {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-between;
		width: 100%;
		font-size: 1.5rem;
		padding: 2rem;
		transition: 0.4s ease-out;
		@media (max-width: 750px) {
      font-size: 1rem;
    }
	}
}

img {
	width: 100%;
	heigth: 150vh;
	object-fit: cover;
}
View Compiled
const header = document.querySelector('.header');
const inView = (entries) => {
  for (const entry of entries) {
    // try logging entry to view all the possible values
    if (entry.boundingClientRect.y < -32) {
      header.classList.add('background--dark'); // for example change the background of the header when the page has scrolled 32 px.
    } else {
      header.classList.remove('background--dark'); 
    }
  }
};
// threshold is just one of the options you can pass in the InteractionObserver
// It determines the amount of triggers while scrolling, it allows an array of numbers between 0 and 1
let threshold = []; 
for (let i = 0; i <= 100; i++) {
  threshold.push(i / 100);
}

const observePageHeader = new IntersectionObserver(inView, { threshold });

// observing the element that has .header as a class
observePageHeader.observe(header);
View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.