Trigger Events When An Elements Enters And Leaves The Boundary – Bounds.js

Category: Javascript , Recommended | July 2, 2019
Author:ChrisCavs
Views Total:690 views
Official Page:Go to website
Last Update:July 2, 2019
License:MIT

Preview:

Trigger Events When An Elements Enters And Leaves The Boundary – Bounds.js

Description:

Bounds.js is a pure JavaScript library to detect boundary asynchronously that allows you to do something when an element enters or leaves the boundary of a specific container.

Useful for image lazy loading, infinite scroll view, and much more. The library requires IntersectionObserver API. You might need a polyfill for legacy browsers.

How to use it:

Install and import the Bounds.js package.

# NPM
$ npm install bounds.js --save
import Bound from 'bounds.js'

Define the element to detect if it enters or leaves a specific element.

const image = document.querySelector('img')
const container = document.querySelector('.container')
const whenImageEnters = (ratio) => {
      // do something
}
const whenImageLeaves = (ratio) => {
      // do something
}

Initialize the Bounds.js library.

const boundary = Bound({
      root: container
})

Start detecting the boundary and trigger events when your images or leave the boundary of the container.

boundary.watch(image, whenImageEnters, whenImageLeaves)

All default options.

const boundary = Bound({
      // top container
      root: window,
      // margins in pixels to trigger the events
      margins: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      // between 0.0 and 1.0
      threshold: 0.0,
      // fired when a element enters or exits the boundary
      onEmit: () => {}
      
})

Unwatch the element.

boundary.unwatch(image)

Check if the element is inside the boundary.

boundary.check(image)

Reset the library.

boundary.reset()

You Might Be Interested In:


Leave a Reply