Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active November 8, 2017 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolanlawson/91515336dcf019e455f5b12dbcc8acc8 to your computer and use it in GitHub Desktop.
Save nolanlawson/91515336dcf019e455f5b12dbcc8acc8 to your computer and use it in GitHub Desktop.
IntersectionObserver test (padding)
<!doctype html>
<html lang="en">
<head>
<title>IntersectionObserver test (padding)</title>
<style>
body {
margin: 0 auto;
padding: 10px;
max-width: 800px;
}
.flex {
display: flex;
}
.container {
width: 200px;
height: 600px;
overflow-y: scroll;
padding: 50px;
}
.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 test (padding)</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(`onObserve event! thresholds: ${JSON.stringify(thresholds)}, id: ${id}, isIntersecting: ${isIntersecting}, intersectionRatio: ${intersectionRatio}`)
})
}
const observer = new IntersectionObserver(onObserve, {
root: $('.container'),
rootMargin: '0px 100%',
threshold: 0
})
observer.observe($('#box3'))
function jsonifyGBCR(el) {
var rect = el.getBoundingClientRect()
return {
left: rect.left,
top: rect.top,
height: rect.height,
width: rect.width
}
}
log('container\'s gBCR: ' + JSON.stringify(jsonifyGBCR($('.container'))))
setTimeout(() => {
log('scrolled down')
$('.container').scrollTop = 250
setTimeout(() => {
log('scrolled to top')
$('.container').scrollTop = 0
}, 400)
}, 400)
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment