JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>rootMargin test</title>
<style>
* {
margin: 0;
padding: 0;
}
h2 {
margin-top: 20px;
}
.container {
position: relative;
height: 200px;
overflow-y: scroll;
background: lightcoral;
}
.pad {
height: 400px;
background-color: lightgreen;
}
.observee {
height: 100px;
background-color: lightblue;
}
</style>
</head>
<body>
<h1>
Scroll over the two green containers below to trigger intersections
</h1>
<h2>
rootMargin - trigger when observee element is 50px within the root
</h2>
<div id="root-container" class="container">
<div class="pad"></div>
<div id="root-observee" class="observee">
</div>
</div>
<h2>
threshold - trigger when 65% of the observee element within the root
</h2>
<div id="threshold-container" class="container">
<div class="pad"></div>
<div id="threshold-observee" class="observee"></div>
</div>
<script>
const rootMarginobserver = new IntersectionObserver(
function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
document.querySelector('#root-observee').innerText = 'Intersected';
} else {
document.querySelector('#root-observee').innerText = 'Not Intersected';
}
});
}, {
root: document.querySelector('#root-container'),
rootMargin: '0px 0px -50px'
}
);
rootMarginobserver.observe(document.querySelector('#root-observee'));
const thresholdObserver = new IntersectionObserver(
function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
...