jQuery Appear Plugin-DETECT ELEMENTS
When an element scrolls into view or otherwise becomes visible to the user, it fires a custom ‘appear’ event. During startup, use the offsetTop and offsetLeft option settings. Secondly, add the custom data attributes shown below and offset-top and offset-left to DOM Nodes.
Example 1.1:
$('#myEl').scrolling({ offsetTop: 100 });
You can use $.checkScrolling to trigger an appearance check().
Example 1.1.1:
<div id="top" data-offset-top="100">...</div>
You may also use a custom scrollin jQuery filter to manually verify if an element is inside the viewport.
Example 1.1.2:
$('selector').is(':scrollin')
IntersectionObserver API
Using an observer, you can quickly verify if an element is visible in the viewport or any scrollable container. It is no longer necessary to attach a scroll event and manually verify the event callback, which is more convenient.
var observer = new IntersectionObserver(onIntersection, {
root: null, // default is the viewport
threshold: .5
})
// When an intersection changes, a callback is triggered.
function onIntersection(entries, opts){
entries.forEach(entry =>
entry.target.classList.toggle('visible', entry.isIntersecting)
)
}
// To observe an element, use the observer.
observer.observe( document.querySelector('.box') )
// stop observing:
// observer.unobserve(entry.target)
span{ position:fixed; top:0; left:0; }
.box{ width:100px; height:100px; background:red; margin:1000px; transition:.75s; }
.box.visible{ background:green; border-radius:50%; }
We start by defining the observer instance. The .5 represents the percentage of the target’s visible area and is triggered onIntersection.
JAVASCRIPT ELEMENT DETECTION METHOD
Example using JavaScript:
window.addEventListener('scroll', function() {
var element = document.querySelector('#user-view');
var position = element.getBoundingClientRect();
if(position.top >= 0 && position.bottom <= window.innerHeight) {
console.log('Element is fully visible in screen');
}
if(position.top < window.innerHeight && position.bottom >= 0) {
console.log('Partial View');
}
});
Example using JavaScript(REACT):
componentDidMount() {
window.addEventListener('scroll', this.isScrolledIntoView);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.isScrolledIntoView);
}
isScrolledIntoView() {
var element = document.querySelector('.element');
var position = element.getBoundingClientRect();
if (position.top >= 0 && position.bottom <= window.innerHeight) {
console.log('Element is fully visible in screen');
}
if (position.top < window.innerHeight && position.bottom >= 0) {
console.log('Element is partially visible in screen');
}
}