Track The Position Of Elements Using Intersection Observer – scroller

Category: Javascript , Recommended | January 24, 2019
Author:rdmurphy
Views Total:1,313 views
Official Page:Go to website
Last Update:January 24, 2019
License:MIT

Preview:

Track The Position Of Elements Using Intersection Observer – scroller

Description:

scroller is a JavaScript library which uses Intersection Observer API to monitor the page location of a series of elements for scroll telling.

How to use it:

Install & import the scroller.

# NPM
$ npm install @newswire/scroller --save
import Scroller from '@newswire/scroller';

Or directly include the UMD version of the scroller in the document.

<script src="https://unpkg.com/@newswire/scroller/dist/index.umd.js"></script>

Initialize the library and specify the elements to be considered scenes of this Scroller.

<div class="container">
  <div class="scene"></div>
  <div class="scene"></div>
  <div class="scene"></div>
  <div class="scene"></div>
  <div class="scene"></div>
  ...
</div>
const myScroller = new Scroller({
      scenes: document.querySelectorAll('.scene'),
});

Specify the containing element of all the scenes, this gets added to the Intersection Observer instance and additionally fires its own events.

const myScroller = new Scroller({
      scenes: document.querySelectorAll('.scene'),
      container: document.querySelectorAll('.container')
});

Specify how far from the top/bottom of the viewable area to trigger enters/exits of scenes, represented as a value between 0 and 1.

const myScroller = new Scroller({
      scenes: document.querySelectorAll('.scene'),
      offset: .5
});

Event handlers.

// triggered every time a scene crosses the threshold
myScroller.on('scene:enter', d => {
  d.element.classList.add('active');
});
// triggered every time a scene exits the threshold
myScroller.on('scene:exit', d => {
  d.element.classList.remove('active');
});
// triggered every time the container crosses the threshold
myScroller.on('container:enter', d => {
  d.element.classList.add('active');
});
// triggered every time the container exits the threshold
myScroller.on('container:exit', d => {
  d.element.classList.remove('active');
});
// on init
myScroller.on('init', () => {
  console.log('Ready');
});

You Might Be Interested In:


Leave a Reply