obzerv

A convenient wrapper around IntersectionObserver for tracking element position relative to the viewport.

  • obzerv

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
obzerv
1010.0.15 years ago5 years agoMinified + gzip package size for obzerv in KB

Readme

obzerv
obzerv on NPM obzerv Downloads on NPM Standard JavaScript Style
A convenient wrapper around IntersectionObserver for tracking element position relative to the viewport.

Install

$ npm i obzerv --save

API

.create(options)

Accepts a config object with callback and offset properties. Returns an observer instance with a track function used to add nodes to the observer.
import obzerv from 'obzerv'

// example callback: lazy loading an image
const callback = (node, inview, untrack) => {
  // exit early if image not in viewport
  if (!inview) {
    return
  }

  // set src attribute of the image
  node.setAttribute('src', node.getAttribute('data-src'))

  // stop tracking image, because load attempt has been initiated
  untrack()
}

// create an observer instance
const observer = obzerv.create({
  callback,
  offset: 25
})

// add all .box elements to the observer
Array
  .from(document.querySelectorAll('.box'))
  .forEach(box => observer.track(box))

License

MIT. © 2017 Michael Cavalea