Skip to content

Instantly share code, notes, and snippets.

@ryonakae
Last active August 24, 2018 04:30
Show Gist options
  • Save ryonakae/81ecf6fa6311bf4f7207fefef06c46b4 to your computer and use it in GitHub Desktop.
Save ryonakae/81ecf6fa6311bf4f7207fefef06c46b4 to your computer and use it in GitHub Desktop.
Intersection Observer Example
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<script src="dist/main.js"></script>
<style>
.target {
width: 200px;
height: 500px;
margin: 1000px 0;
background-color: gray;
transition: all 1s ease;
}
.hide {
opacity: 0.1;
}
.show {
opacity: 1;
}
</style>
</head>
<body>
<p>IntersectionObserver</p>
<div class="target hide">
<h2>target</h2>
</div>
</body>
</html>
{
"license": "MIT",
"scripts": {
"dev": "webpack --mode development --module-bundle js=babel-loader --watch",
"build": "webpack --mode production --module-bundle js=babel-loader"
},
"babel": {
"presets": [
"@babel/preset-env"
]
},
"dependencies": {
"intersection-observer": "^0.5.0"
},
"devDependencies": {
"@babel/core": "^7.0.0-rc.2",
"@babel/preset-env": "^7.0.0-rc.2",
"babel-loader": "^7.1.5",
"webpack": "^4.17.1",
"webpack-cli": "^3.1.0"
}
}
// import polyfill
import 'intersection-observer'
window.addEventListener('DOMContentLoaded', init, false)
function init () {
const observer = new IntersectionObserver(entries => {
for (const entry of entries) {
check(entry)
}
})
const targets = document.querySelectorAll('.target')
for (const target of targets) {
observer.observe(target)
}
}
function check (entry) {
if (entry.intersectionRatio > 0) {
console.log('show')
entry.target.classList.add('show')
entry.target.classList.remove('hide')
} else {
console.log('hide')
entry.target.classList.remove('show')
entry.target.classList.add('hide')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment