Skip to content

Instantly share code, notes, and snippets.

@thangman22
Last active September 5, 2017 19:55
Show Gist options
  • Save thangman22/52770da9e48486197c02019bdda34814 to your computer and use it in GitHub Desktop.
Save thangman22/52770da9e48486197c02019bdda34814 to your computer and use it in GitHub Desktop.
IntersectionObserver.js
// ประกาศสร้าง 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