Skip to content

Instantly share code, notes, and snippets.

@MWarCZ
Last active November 4, 2024 06:17
Show Gist options
  • Save MWarCZ/95537b36fee30113fc1526501b03cf66 to your computer and use it in GitHub Desktop.
Save MWarCZ/95537b36fee30113fc1526501b03cf66 to your computer and use it in GitHub Desktop.
Intersection observer with detection of vertical scroll direction.
function createIntersectionObserver(callback, opts = { root: null, rootMargin: '0px', threshold: 0}) {
var previousY = new Map();
var observer = new IntersectionObserver(function(entries, observer){
console.log(entries);
entries.forEach(function (entry) {
var currY = entry.boundingClientRect.y;
var prevY = previousY.get(entry.target);
if(currY<prevY) { /* scroll down */ entry.scrollDirectionY = 'down'; }
if(currY>prevY) { /* scroll up */ entry.scrollDirectionY = 'up'; }
callback(entry, observer, entries);
previousY.set(entry.target, currY);
});
}, opts)
return observer;
}
var observer = createIntersectionObserver(function(entry){
if (entry.isIntersecting) {
entry.target.classList.add("a-show");
}
else {
if(entry.scrollDirectionY == 'up') {
entry.target.classList.remove("a-show");
}
}
});
document.querySelectorAll('.table-list tr').forEach(function(el){ observer.observe(el); })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment