element-visibility-observer
v1.0.1
Published
A wrapper of IntersectionObserver for detecting element visibility in viewport.
Downloads
6
Maintainers
Readme
ElementVisibilityObserver
This is a wrapper of IntersectionObserver
JavaScript API for detecting element visibility.
No dependencies. But currently (2018) Safari (and IE) is not supporting IntersectionObserver, you will need IntersectionObserver polyfill. Please consider the limitations of the polyfill and check the latest browser support before use in production.
Installation
npm install element-visibility-observer
or
yarn add element-visibility-observer
Polyfills you will need
npm install intersection-observer @babel/polyfill
or
yarn add intersection-observer @babel/polyfill
- intersection-observer:
IntersectionObserver
support in Safari and IE - @babel/polyfill:
Array.from
andObject.assign
if you need IE support
Usage
Basic
HTML
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
JavaScript
const elementVisibilityObserver = new ElementVisibilityObserver()
elementVisibilityObserver.observe(
'.box',
target => target.classList.add('visible'), // onVisible
target => target.classList.remove('visible'), // onHidden
);
Get current visibility ratio
Lazyload
API
Constructor
new ElementVisibilityObserver([visibleRatio [, observerOption]])
visibleRatio
- Type:
Number
from0
to1
- Default:
0.25
- Element is defined as "visible" when more then 25% of the element is visible in viewport (or root element).
- Type:
observerOption
- Type:
Object
- Default:
{ root: null, rootMargin: '0px', threshold: [0, this.visibleRatio, 1] }
- Type:
Method
.observe(target [, onVisible [, onHidden]])
Observe all target elements.
- target:
String
of CSS selector ||NodeList
||Element
- onVisible(target, entry, observer): Callback
function
triggers when the element is visible. - onHidden(target, entry, observer): Callback
function
triggers when the element is not visible.- target:
IntersectionObserverEntry.target
- entry:
IntersectionObserverEntry
- observer:
IntersectionObserver
- target:
.disconnect()
Destroy all observers
Properties
.observers
Array
of IntersectionObserver