Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Created July 29, 2020 01:43
Show Gist options
  • Save tkfm-yamaguchi/8196f29bbd3714546e893ac82de6728b to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/8196f29bbd3714546e893ac82de6728b to your computer and use it in GitHub Desktop.
IntersectionObserver memo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Intersection Observer</title>
<style>
#outer {
height: 500px;
width: calc(100vw - 100px);
margin-top: calc((100vh - 500px)/2);
margin-left: auto;
margin-right: auto;
overflow-y: scroll;
border: 1px solid #000;
}
#inner-top {
background-color: #392734;
color: #aefddf;
}
#inner-bottom {
height: 100px;
background-color: #defa33;
color: #223932;
line-height: 20px;
padding-top: calc((100px - 20px)/2);
text-align: center;
}
</style>
</head>
<body>
<section id="outer">
<section id="inner-top">
a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a a<br/>a
</section>
<section id="inner-bottom">
When this is shown, observer reacts something!
</section>
</section>
<script>
document.addEventListener('DOMContentLoaded', () => {
const elemRoot = document.getElementById('outer');
const elemTarget = document.getElementById('inner-bottom');
const options = {
root: elemRoot,
rootMargin: '0px',
threshold: 1.0,
};
const callback = (entries, observer) => {
const entry = entries[0];
if (entry.isIntersection) {
console.log('shown', entry);
}
}
const observer = new IntersectionObserver(callback, options);
observer.observe(elemTarget);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment