Intersection Observer
HTML
<script src="//cdn.rawgit.com/w3c/IntersectionObserver/9a44a313/polyfill/intersection-observer.js"></script>
<input type="button" onclick="appendDiv()" value="Append Div"/>
<input type="button" onclick="removeDiv()" value="Remove Div"/>
<!-- <input type="button" onclick="takeRecords()" value="Take Records"/> -->
JavaScript
//https://jsfiddle.net/Konrud/o4ha0t97/
const observerOptions = {
threshold: [0, 1]
};
const observer = new IntersectionObserver(handleIntersection, observerOptions);
function handleIntersection(entries, observerObj) {
console.log(entries);
console.log(observerObj);
entries.forEach(function(entry, i) {
if(!entry.isIntersecting) {
console.log("!!!! fully hidden "+entry.target.id + " " + entry.intersectionRatio*100+'%');
}
else if(entry.intersectionRatio >= 1/*can be little bit greater then 1, why?*/)
{
console.log("!!!! fully shown "+entry.target.id + " " + entry.intersectionRatio*100+'%');
}
else
{
console.log("!!!! partially shown "+entry.target.id + " " + entry.intersectionRatio*100+'%');
}
});
};
var id = 0;
window.appendDiv = function()
{
var div = document.createElement('div');
div.id = ''+(++id);
div.innerHTML=div.id;
div.style.backgroundColor='red';
div.style.width='100px';
div.style.height='100px';
div.style.margin='3px';
observer.observe(div);
document.body.appendChild(div);
}
window.removeDiv = function()
{
var div = document.getElementById(''+(id--));
document.body.removeChild(div);
}