JSPM

element-visibility-observer

1.0.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1
  • Score
    100M100P100Q31689F
  • License MIT

A wrapper of IntersectionObserver for detecting element visibility in viewport.

Package Exports

  • element-visibility-observer

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (element-visibility-observer) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

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

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:
    {
        root: null,
        rootMargin: '0px',
        threshold: [0, this.visibleRatio, 1]
    }

Method

.observe(target [, onVisible [, onHidden]])

Observe all target elements.

.disconnect()

Destroy all observers

Properties

.observers

Array of IntersectionObserver