ViewportDetector is a lightweight (1kb Gzipped) dependancy free library to detect if an element is shown in the viewport (or another container) or not. It use requestAnimationFrame API to be without any impact on the performance.
Just include the minified version of ViewportDetector.js on your website :
<script src="viewportdetector/build/viewportdetector.min.js"></script>
To use viewport detector, create a new instance :
var detector = new ViewportDetector(
selector: '.element',
callback: myCallback
);
Here is the list of available parameters :
Name | Default value | Description |
callback | Null | Callback to execute on visibility change. Callback receive 2 parameters, the DOMElement and the Visibility (boolean). Required |
selector | Null | Element selector to observe. Required |
opts.marge | Null | Marge to expand or reduce element detection size. |
opts.container | window | Container selector within detection should happen. |
Here is the list of available APIs :
Name | Description |
add(selector, callback, opts) | Add en element to detect into a instance of ViewportDetector. |
Default parameters :
var cb = function(el, visibility) {
if (visibility) {
el.classList.add('show');
} else {
el.classList.remove('show');
}
document.querySelector('.visibility').innerHTML = visibility ? 'true' : 'false';
}
var example = new ViewportDetector('.element', cb, {container: '.demo1'});
Visibility
false
With marge parameter, element is detected X pixels before appearing into viewport :
var example = new ViewportDetector('.element', cb, {marge: 100, container: '.demo2'});
Visibility
false
Multiple elements :
var example = new ViewportDetector([
{
selector: '.element_1',
callback: cb1,
opts: {container: '.demo3'}
},
{
selector: '.element_2',
callback: cb2,
opts: {
marge: 100,
container: '.demo3'
}
}
]);
example.add('.element_3', cb3, {container: '.demo3'});
Element 1
false
Element 2
false
Element 3
false