Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!doctype html>
- <html lang="en">
- <head>
- <title>IntersectionObserver demo</title>
- <style>
- body {
- margin: 0 auto;
- padding: 10px;
- max-width: 800px;
- display: flex;
- }
- .container {
- width: 200px;
- height: 600px;
- overflow-y: scroll;
- }
- .box {
- height: 100px;
- 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>
- <div class="container">
- <div id="box0" class="box">
- Hello
- </div>
- <div id="box1" class="box">
- this
- </div>
- <div id="box2" class="box">
- is
- </div>
- <div id="box3" class="box">
- a
- </div>
- <div id="box4" class="box">
- list
- </div>
- <div id="box5" class="box">
- of
- </div>
- <div id="box6" class="box">
- items
- </div>
- <div id="box7" class="box">
- using
- </div>
- <div id="box8" class="box">
- Intersection
- </div>
- <div id="box9" class="box">
- Observer
- </div>
- <div id="box10" class="box">
- Here
- </div>
- <div id="box11" class="box">
- are
- </div>
- <div id="box12" class="box">
- some
- </div>
- <div id="box13" class="box">
- more
- </div>
- <div id="box14" class="box">
- elements.
- </div>
- </div>
- <pre class="display">Output:
- </pre>
- <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 id = entry.target.id
- log(`id: ${id}, isIntersecting: ${isIntersecting}, intersectionRatio: ${intersectionRatio}`)
- })
- }
- const observer = new IntersectionObserver(onObserve, {
- root: $('.container'),
- rootMargin: '0px 100%',
- threshold: 0
- })
- $$('.box').forEach(el => {
- observer.observe(el)
- })
- })
- </script>
- </body>
- </html>
Add Comment
Please, Sign In to add comment