Last active
September 5, 2017 19:55
-
-
Save thangman22/52770da9e48486197c02019bdda34814 to your computer and use it in GitHub Desktop.
IntersectionObserver.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ประกาศสร้าง instance ของ IntersectionObserver พร้อมบอกด้วยว่า ก่อนแสดงผล 50 pixel ให้ trigger ไปหา callback | |
const contatiner = document.getElementById('image') | |
const observer = new IntersectionObserver(onIntersection, {rootMargin: '50px 0px'}) | |
// บอกว่าให้เฝ้า id="image" เอาไว้ | |
observer.observe(contatiner) | |
function onIntersection (entry) { | |
let element = entry[0] | |
// ถ้า ratio ของ element นั้นมากกว่า 0 ให้แสดงผลและ เลือก | |
if(element.intersectionRatio > 0) { | |
//แสดงผลตรงนี้ | |
//หลังจาก แสดงผลให้เลิก observe element นั้นไป | |
observer.unobserve(element.target) | |
observer.disconnect() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment