Skip to content

Instantly share code, notes, and snippets.

@nolanlawson

nolanlawson/index.html

Last active Jul 27, 2017
Embed
What would you like to do?
IntersectionObserver event demo (Firefox double-fire event)
<!doctype html>
<html lang="en">
<head>
<title>IntersectionObserver event demo (Firefox double-fire event)</title>
<style>
body {
margin: 0 auto;
padding: 10px;
max-width: 800px;
}
.flex {
display: flex;
}
.container {
width: 200px;
height: 600px;
overflow-y: scroll;
}
.box {
height: 300px;
display: flex;
justify-content: center;
align-items: center;
border: none;
margin: 0;
padding: 0;
}
.box:nth-child(even) {
background: #aaa;
}
.box:nth-child(odd) {
background: #ccc;
}
.display {
width: 200px;
height: 100%;
margin-left: 50px;
}
</style>
</head>
<body>
<h1>IntersectionObserver event demo (Firefox double-fire event)</h1>
<div class="flex">
<div class="container">
<div id="box0" class="box">
Hello
</div>
<div id="box1" class="box">
world
</div>
<div id="box2" class="box">
Intersection
</div>
<div id="box3" class="box">
Observer
</div>
</div>
<pre class="display">Output:
</pre>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const $ = document.querySelector.bind(document)
const $$ = _ => Array.from(document.querySelectorAll(_))
const display = $('.display')
function log(str) {
display.textContent += (str || '') + '\n'
}
function onObserve(entries) {
entries.forEach(entry => {
const {
isIntersecting,
intersectionRatio
} = entry
const thresholds = observer.thresholds
const id = entry.target.id
log(`thresholds: ${JSON.stringify(thresholds)}, id: ${id}, isIntersecting: ${isIntersecting}, intersectionRatio: ${intersectionRatio}`)
})
}
const observer = new IntersectionObserver(onObserve, {
root: $('.container'),
rootMargin: '0px 100%',
threshold: 0
})
$$('#box3').forEach(el => {
observer.observe(el)
})
setTimeout(() => {
log('scrolled to 300')
$('.container').scrollTop = 300
setTimeout(() => {
log('scrolled to 301')
$('.container').scrollTop = 301
setTimeout(() => {
log('scrolled to top')
$('.container').scrollTop = 0
}, 1000)
}, 1000)
}, 1000)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.