Git Product home page Git Product logo

bounds.js's Introduction

Bounds.js

bounds.js on NPM

Asynchronous boundary detection. 1KB, no dependencies.

Demo.

Why

Whether you're lazy-loading images, implementing infinite-scroll, or avoiding an ex-lover... it's important to set boundaries.

Historically, boundary detection required a mix of event handlers, loops, and calls to getBoundingClientRect. Since these operations run on the main thread, performance would suffer.

Bounds.js defies these expectations, providing a simple and powerful API. It detects intersections between elements asynchronously, keeping complex operations off the main thread and improving performance.

Usage

Bounds.js was developed with a modern JavaScript workflow in mind. To use it, it's recommended you have a build system in place that can transpile ES6 and bundle modules.

Follow these steps to get started:

  1. Install
  2. How to Use
  3. Options
  4. API
  5. Browser Support

Install

Using NPM, install bounds.js, and save it to your package.json dependencies.

$ npm install bounds.js --save

Then import, naming it according to your preference.

import Bound from 'bounds.js'

How to Use

The first step is to create a new boundary using bounds.js. To do so, call it and pass in your desired options. Each option and its default is explained in the options section below.

const boundary = Bound()   // initialize with default options

The second step is to have your new boundary watch for certain elements on you webpage. When these elements intersect with the boundary, a callback is executed. See an example below:

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

boundary.watch(image, whenImageEnters, whenImageLeaves)

Now that we've covered the basics, lets delve into the options and API.

Options

You are not required to pass any options during boundary creation. All options come with sensible defaults, shown below:

// default options
{
  root: window,       // the top-level document's viewport
  margins: {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  },
  threshold: 0.0,
  onEmit: () => {}    // no-op
}

Explanation of each option follows:

root

Accepts a DOM node.

The root is the element for which we are creating the boundary. Events will be emitted whenever a watched element enters/exits the root element.

margins

Accepts a mapping, where values are stated in pixels.

You can specify a top, right, bottom, or left margin to add to the root's bounding box. This affects detection, NOT style on the root element. For example:

const boundary = Bound({
  margins: {
    bottom: 100,
  }
})

The above boundary will fire a callback for any watched element that gets within 100px of its bottom border.

threshold

Accepts a number between 0.0 and 1.0.

The ratio of intersecting area required before a callback is made. A threshold of 0.0 means that if even a single pixel of a watched element enters the boundary, a callback is made. A threshold of 1.0 means that every pixel of a watched element must be inside the boundary before a callback is made.

onEmit

Accepts a function or anonymous function.

The provided callback will be executed whenever any watched element enters or exits the boundary, once all individual callbacks have executed. This is a useful option if you'd like some action to take place no matter what element enters/exits your boundary. Here is an example of how it can be used:

const boundary = Bound({
  onEmit: (actions) => {
    if (actions.some(action => action.inside)) {
      console.log('At least one element is inside my boundary')
    }
  }
})

As seen above, the onEmit callback will be passed an argument actions, which is an array of objects representing the actions taken directly beforehand. Each object in actions has the following detail:

{
  el,       // DOM node
  inside,   // boolean
  outside,  // boolean
  ratio     // floating number
}

API

When you create a new boundary with bounds.js, an object with a set of methods will be returned. Those methods are:

Additionally, the bounds.js import object has a static property:

watch(el [, onEnter, onLeave])

Calling watch will instruct your boundary to watch the desired element. When the specified element enters your boundary, the onEnter callback will be executed. When the specified element leaves your boundary, the onLeave callback will be executed.

Each callback is passed 1 argument, ratio, which represents the ratio of the element's bounding box that is inside the boundary.

const boundary = Bound()

const img = document.querySelector('img')
const onImgEnter = (ratio) => {}
const onImgLeave = (ratio) => {}

boundary.watch(img, onImgEnter, onImgLeave)

The watch method will return a data object with the assigned properties. These properties can be mutated. For example, assuming we had the same methods as above:

// you can choose to not initially provide callbacks
const imgOptions = boundary.watch(img)

// later, you can assign new callbacks
imgOptions.onEnter = onImgEnter
imgOptions.onLeave = onImgLeave

unWatch(el)

The unWatch method will instruct your boundary to stop watching a certain element. Callbacks for that element will no longer be executed. The boundary instance will be returned.

check(el)

The check method will return a boolean, indicating if the provided element is currently inside the boundary. The check is based on history, which starts once you watch the element. If the element is not currently being watched, check will return undefined.

clear()

The clear method will effectively unWatch all elements for the boundary, destroy all history for the elements the boundary was watching, and ensure that no events are emitted by the boundary going forward.

Bound.checkCompatibility()

The static checkCompatibility method will throw an error if Bounds.js is not supported in the user's browser.

Browser Support

Bounds.js depends on the following browser APIs:

Consequently, it supports the following natively:

  • Chrome 51+
  • Firefox 55+
  • Safari 12.1+
  • Edge 15+
  • iOS Safari 12.2+
  • Chrome for Android 51+
  • Opera - Supported
  • IE - No Support

For browsers that do not currently support IntersectionObserver, consider a popular polyfill that has great browser support.

License

MIT. © 2019 Christopher Cavalea

bounds.js's People

Contributors

chriscavs avatar

Stargazers

Oleg Tishkin avatar Danny Colin avatar Raoul Simionas avatar  avatar  avatar Amir Haytham Salama avatar MA avatar TofuBoy avatar Jo avatar Erwin avatar M Haidar Hanif avatar  avatar xtcVFIlH avatar 王洪莹 avatar Burak avatar qi avatar ChasLui avatar  avatar wheeljs avatar Yasin ATEŞ avatar Juanjo Dominguez avatar Nikolay avatar Vlad Alexandru avatar xch1029 avatar  avatar Nigel Britton avatar zoe avatar Fatih Eğriboz avatar Jiri Melcak avatar Jonathan Giardino avatar 辻 修一 avatar wfd2018 avatar Xvezda avatar Binsar Dwi Jasuma avatar RyanC avatar ishan avatar Piotr Błażejewicz (Peter Blazejewicz) avatar Samuel Herrera avatar Brandon Ha avatar BunyIp avatar KaiLee avatar Chris Merina avatar  avatar Maruf Ahmed avatar Alex McCarthy avatar Mehmet Egemen Albayrak avatar  avatar Gilbert Seilheimer avatar Ming avatar  avatar  avatar Ronak Raithatha avatar Jesse Randall avatar Naman Singhal avatar Артур Засеев avatar  avatar Vitaliy Kononov avatar Riad avatar Mehmet Emin Eker avatar Dan Rocha avatar joachim kliemann avatar Marco Pozzato avatar Anthony Garratt avatar John A. Zoidberg avatar  avatar Thram avatar Lachlan D-K avatar Bogdan Dolin avatar Igor Karachentsev avatar SFAT LLC avatar Troy Rhinehart avatar Ahmad Moghazi avatar Guilherme Felix da Silva Maciel avatar Niringiye avatar Vinicius Lourenço avatar  avatar Philip Warkentien II avatar Isaac Preston avatar Tom avatar Scott Wade avatar Cody Marcoux avatar Roman Timashev avatar Alexey avatar Max Lawrence avatar Anton Sirotkin avatar soojubm avatar Ilham Wahabi avatar Jose Felix  avatar Hallur Kárason Nielsen avatar Wouter avatar Nguyen Tran avatar Matteo Manzinello avatar  avatar Filippo Mangione avatar Wu Weixin avatar Teun de Kleijne avatar patrick cook avatar Mohamed Samir avatar Alican avatar Toni avatar

Watchers

Vitaly Rotari avatar  avatar Phạm Thanh Bình avatar rene404 avatar Jose Eduardo Kimura avatar Sebastian Pietrzak avatar  avatar Niringiye avatar  avatar Mattia M. avatar Victor Schedlyn GUTT avatar Danil Emelyanenko avatar

bounds.js's Issues

TypeError when options parameter is not provided

When invoking bound.js without an options parameter like ...

const windowBound = Bounds();

... I get the error bounds.js:1 Uncaught TypeError: Cannot read property 'root' of undefined.

Using an empty param (const windowBound = Bounds({});) as a workaround.

Cannot set property 'history' of undefined

Hi,
in our error logging system we've got messages complaining that
Cannot set property 'history' of undefined

This is the only place in the code where history is assigned.

data.history = event.isIntersecting

This happens only in Chrome versions 51-57 which are known to have missing isIntersecting
https://caniuse.com/#feat=intersectionobserver
and this should be polyfilled correctly
https://github.com/w3c/IntersectionObserver/blob/d3eece49746574f43798d411d9fea2968251b075/polyfill/intersection-observer.js#L23-L34

I was trying to use Chromium of those old versions but nothing fails with the polyfill included.

Also the demo page
https://chriscavs.github.io/bounds-demo/
in this Chromium version (macOS 53.0.2767.0 (64-bit) to be exact) does not correctly loads lazy loading images. Top example works ok. I see that polyfill is included in the bundle.
https://chriscavs.github.io/bounds-demo/dist/bundle.js
Maybe that's somehow related. No errors in Chromium console though.

Chromium versions if someone would like to test it.
https://commondatastorage.googleapis.com/chromium-browser-snapshots/index.html

Any ideas what might be going on and why data might be undefined?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.