1.0.1 • Published 6 years ago

element-visibility-observer v1.0.1

Weekly downloads
4
License
MIT
Repository
github
Last release
6 years ago

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

Usage

Basic

Demo on Codepen

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

Demo on Codepen

Lazyload

Demo on Codepen

API

Constructor

new ElementVisibilityObserver([visibleRatio , observerOption])

  • visibleRatio - Type: Number from 0 to 1 - Default: 0.25 - Element is defined as "visible" when more then 25% of the element is visible in viewport (or root element).
  • observerOption - Type: Object - Default:
    	```javascript
    	{
    		root: null,
    		rootMargin: '0px',
    		threshold: [0, this.visibleRatio, 1]
    	}
    	```
    	- See [MDN - IntersectionObserver#Properties](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver#Properties).

Method

.observe(target [, onVisible , onHidden])

Observe all target elements.

.disconnect()

Destroy all observers

Properties

.observers

Array of IntersectionObserver