Cross-platform Viewport Checker With Pure JavaScript – emergence.js

Category: Javascript , Recommended | October 11, 2018
Author: xtianmiller
Views Total: 504
Official Page: Go to website
Last Update: October 11, 2018
License: MIT

Preview:

Cross-platform Viewport Checker With Pure JavaScript – emergence.js

Description:

emergence.js is a cross-platform, high-performance viewport checker library which detects if HTML elements are in the viewport, and performs custom actions when the elements are visible and/or hidden.

Installation:

# NPM
$ npm install emergence.js --save

# Bower
$ bower install emergence.js --save

How to use it:

Insert the minified version of the emergence.js into the web page.

<script src="dist/js/emergence.min.js"></script>

Initialize the emergence.js and you’re ready to go.

emergence.init({
  // options here
});

Add the data-emergence="hidden" attribute to any element you want to watch for the scroll position.

<div class="myElement" data-emergence="hidden"></div>

Apply custom CSS styles (e.g. CSS3 based animations) to the element when it becomes visible or invisible as you scroll the web page.

.myElement[data-emergence=hidden] {
  /* ... */
}

.myElement[data-emergence=visible] {
  /* ... */
}

Or perform custom actions when the element becomes visible or invisible as you scroll the web page.

emergence.init({
  callback: function(element, state) {
    if (state === 'visible') {
      // do something
    } else if (state === 'reset') {
      // do something
    } else if (state === 'noreset') {
      // do something
    }
  }
});

Possible options to customize the emergence.js library.

emergence.init({

  // parent container
  container: window,

  // resets state 
  reset: true,

  // false = disable the library on phones and tablets
  handheld: true,

  // in milliseconds
  throttle: 250,

  // determine how much of the element needs to be within the viewport to count as "visible"
  elemCushion: 0.15,

  // offsets in pixels
  offsetTop: 0,
  offsetRight: 0,
  offsetBottom: 0,
  offsetLeft: 0
  
});

API methods.

// Refire visibility checks outside of the load, scroll and resize events already baked into the plugin
emergence.engage();

// Disable Emergence
emergence.disengage();

Changelog:

10/11/2018

  • v1.1.2

Leave a Reply