Convert Figma logo to code with AI

stutrek logoscrollmonitor

A simple and fast API to monitor elements as you scroll

3,297
243
3,297
20

Top Related Projects

4,649

Get notified when a DOM element enters or exits the viewport. :eyes:

10,382

Waypoints is a library that makes it easy to execute a function whenever you scroll to an element.

26,486

Animate on scroll library

Animate elements as they scroll into view.

Let your page react to scroll changes.

Quick Overview

ScrollMonitor is a lightweight JavaScript library for monitoring and reacting to element scroll positions in the viewport. It provides an efficient way to track when elements enter, leave, or are partially visible within the browser window, enabling developers to create scroll-based animations and interactions easily.

Pros

  • Small and lightweight, with minimal impact on performance
  • Easy to use API with intuitive methods and callbacks
  • Supports both vertical and horizontal scrolling
  • Works well with modern JavaScript frameworks and vanilla JS

Cons

  • Limited documentation and examples available
  • Not actively maintained (last update was in 2021)
  • May require additional setup for complex scroll-based animations
  • Lacks built-in animation features, focusing primarily on scroll detection

Code Examples

  1. Basic usage to detect when an element enters the viewport:
import scrollMonitor from 'scrollmonitor';

const element = document.querySelector('.my-element');
const watcher = scrollMonitor.create(element);

watcher.enterViewport(() => {
  console.log('Element has entered the viewport');
});
  1. Detecting when an element is fully visible:
const watcher = scrollMonitor.create(element);

watcher.fullyEnterViewport(() => {
  console.log('Element is fully visible');
});
  1. Using offset to trigger events before the element enters the viewport:
const watcher = scrollMonitor.create(element, -100);

watcher.enterViewport(() => {
  console.log('Element is 100px away from entering the viewport');
});

Getting Started

  1. Install ScrollMonitor using npm:
npm install scrollmonitor
  1. Import and use ScrollMonitor in your JavaScript file:
import scrollMonitor from 'scrollmonitor';

const element = document.querySelector('.my-element');
const watcher = scrollMonitor.create(element);

watcher.enterViewport(() => {
  element.classList.add('visible');
});

watcher.exitViewport(() => {
  element.classList.remove('visible');
});

This basic setup will add a 'visible' class to the element when it enters the viewport and remove it when it exits.

Competitor Comparisons

4,649

Get notified when a DOM element enters or exits the viewport. :eyes:

Pros of in-view

  • Lightweight and simple API, making it easy to use for basic scroll detection
  • Supports both vanilla JavaScript and as a jQuery plugin
  • Uses Intersection Observer API for better performance when available

Cons of in-view

  • Limited customization options compared to scrollmonitor
  • Lacks advanced features like custom offsets and direction detection
  • Less actively maintained, with fewer recent updates

Code Comparison

scrollmonitor:

var elementWatcher = scrollMonitor.create(element);
elementWatcher.enterViewport(function() {
    console.log('Element has entered the viewport');
});

in-view:

inView('.selector')
    .on('enter', function(el) {
        console.log('Element has entered the viewport');
    });

Both libraries offer straightforward APIs for detecting when elements enter the viewport. scrollmonitor provides more granular control and additional features, while in-view focuses on simplicity and ease of use. scrollmonitor is more actively maintained and offers a wider range of options for complex scroll-based interactions. in-view, on the other hand, is lighter and may be sufficient for simpler use cases, especially when leveraging the Intersection Observer API for improved performance.

10,382

Waypoints is a library that makes it easy to execute a function whenever you scroll to an element.

Pros of Waypoints

  • More comprehensive feature set, including directional triggers and custom offsets
  • Better documentation and examples, making it easier for beginners to use
  • Wider browser support, including older versions of Internet Explorer

Cons of Waypoints

  • Larger file size, which may impact page load times
  • More complex API, potentially requiring a steeper learning curve
  • Less frequent updates and maintenance compared to ScrollMonitor

Code Comparison

ScrollMonitor:

var elementWatcher = scrollMonitor.create(element);
elementWatcher.enterViewport(function() {
    console.log('Element is in view');
});

Waypoints:

var waypoint = new Waypoint({
  element: document.getElementById('element'),
  handler: function() {
    console.log('Element is in view')
  }
})

Both libraries offer similar functionality for detecting when elements enter the viewport, but Waypoints provides a more object-oriented approach with additional configuration options. ScrollMonitor's API is more straightforward and functional, which may be preferable for simpler use cases.

26,486

Animate on scroll library

Pros of AOS

  • More focused on animations and effects triggered by scrolling
  • Offers a wider variety of pre-built animations out of the box
  • Easier to implement for non-technical users with data attributes

Cons of AOS

  • Less flexible for custom scroll-based behaviors
  • May have a higher performance impact due to more complex animations
  • Limited to element-based triggers, unlike ScrollMonitor's more versatile API

Code Comparison

ScrollMonitor:

var elementWatcher = scrollMonitor.create(element);
elementWatcher.enterViewport(function() {
    console.log('Element is in view');
});

AOS:

<div data-aos="fade-up" data-aos-duration="1000">
    This element will fade up on scroll
</div>

Summary

ScrollMonitor is more lightweight and flexible, ideal for developers who need precise control over scroll-based behaviors. AOS, on the other hand, excels in providing easy-to-use, pre-built animations triggered by scrolling, making it more accessible for designers and non-technical users. The choice between the two depends on the specific project requirements and the level of customization needed.

Animate elements as they scroll into view.

Pros of ScrollReveal

  • More feature-rich, offering advanced animation options and sequencing
  • Better documentation and examples, making it easier for beginners to use
  • Actively maintained with regular updates and bug fixes

Cons of ScrollReveal

  • Larger file size, which may impact page load times
  • More complex API, potentially requiring a steeper learning curve
  • Limited to reveal animations, while ScrollMonitor is more versatile for general scroll tracking

Code Comparison

ScrollReveal:

ScrollReveal().reveal('.headline', {
    delay: 500,
    distance: '50px',
    origin: 'bottom',
    duration: 1000
});

ScrollMonitor:

var elementWatcher = scrollMonitor.create(element);
elementWatcher.enterViewport(function() {
    console.log('Element has entered the viewport');
});

ScrollReveal focuses on creating reveal animations with various options, while ScrollMonitor provides a more general-purpose scroll tracking functionality. ScrollReveal's API is more declarative, while ScrollMonitor uses a callback-based approach. Both libraries serve different purposes and can be chosen based on specific project requirements.

Let your page react to scroll changes.

Pros of ScrollTrigger

  • More lightweight and focused on triggering events based on scroll position
  • Simpler API with easy-to-use methods like trigger and destroy
  • Supports both vertical and horizontal scrolling

Cons of ScrollTrigger

  • Less comprehensive element tracking compared to scrollmonitor
  • Fewer built-in options for handling element visibility and offsets
  • Limited documentation and examples available

Code Comparison

ScrollTrigger:

const trigger = new ScrollTrigger({
  trigger: {
    once: false,
    offset: {
      viewport: {
        x: 0,
        y: 0.25
      }
    },
    toggle: {
      class: {
        in: 'visible',
        out: 'invisible'
      }
    }
  }
});

scrollmonitor:

const elementWatcher = scrollMonitor.create(element, {
  top: 200,
  bottom: -200
});

elementWatcher.enterViewport(function() {
  console.log('Element has entered the viewport');
});

Both libraries offer scroll-based event triggering, but ScrollTrigger focuses on simplicity and lightweight implementation, while scrollmonitor provides more comprehensive element tracking and visibility management. ScrollTrigger's API is more concise, but scrollmonitor offers more granular control over element monitoring and callbacks.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

scrollMonitor

The scroll monitor allows you to receive events when elements enter or exit a viewport. It does this using watcher objects, which watch an element and trigger events. Watcher objects also contain information about the element they watch, including the element's visibility and location relative to the viewport. If your scroll container is an element other than the body you can create a container that creates watchers.

The scroll monitor was designed to be very fast. On each scroll event the DOM is only touched twice, once to find the document height and again to find the viewport top. No variables are declared, nor are any objects, arrays, or strings created. Watchers are very cheap. Create them liberally.

The code is vanilla javascript and has no external dependencies, however the script cannot be put in the head.

Also see the React hooks, React component and the parallax library.

Basic Usage

When the body scrolls

var scrollMonitor = require("scrollmonitor"); // if you're old school you can use the scrollMonitor global.
var myElement = document.getElementById("itemToWatch");

var elementWatcher = scrollMonitor.create( myElement );

elementWatcher.enterViewport(function() {
    console.log( 'I have entered the viewport' );
});
elementWatcher.exitViewport(function() {
    console.log( 'I have left the viewport' );
});

For a scroll container

var containerElement = document.getElementById("container");

var containerMonitor = scrollMonitor.createContainer(containerElement);
// this containerMonitor is an instance of the scroll monitor
// that listens to scroll events on your container.

var childElement = document.getElementById("child-of-container");
var elementWatcher = containerMonitor.create(childElement);

elementWatcher.enterViewport(function() {
    console.log( 'I have entered the viewport' );
});
elementWatcher.exitViewport(function() {
    console.log( 'I have left the viewport' );
});

Note: an element is said to be in the viewport if it is scrolled into its parent, it does not matter if the parent is in the viewport.

Demos

Watcher Objects

Create watcher objects with scrollMonitor.create( watchItem ). An optional second argument lets you receive events before or after this element enters the viewport. See "Offsets".

watchItem can be one of the following:

  • DOM Element - the watcher will watch the area contained by the DOM element.
  • Object - obj.top and obj.bottom will be used for watcher.top and watcher.bottom.
  • Number - the watcher will watch a 1px area this many pixels from the top. Negative numbers will watch from the bottom.
  • jQuery object - it will use the first DOM element.
  • NodeList or Array - it will use the first DOM element.
  • string - it will use the string as a CSS selector and watch the first match.

Watchers are automatically recalculated on the first scroll event after the height of the document changes.

Events

Element watchers trigger six events:

  • visibilityChange - when the element enters or exits the viewport.
  • stateChange - similar to visibilityChange but is also called if the element goes from below the viewport to above it in one scroll event or when the element goes from partially to fully visible or vice versa.
  • enterViewport - when the element enters the viewport.
  • fullyEnterViewport - when the element is completely in the viewport [1].
  • exitViewport - when the element completely leaves the viewport.
  • partiallyExitViewport - when the element goes from being fully in the viewport to only partially [2].
  1. If the element is larger than the viewport fullyEnterViewport will be triggered when the element spans the entire viewport.
  2. If the element is larger than the viewport partiallyExitViewport will be triggered when the element no longer spans the entire viewport.

Properties

  • elementWatcher.isInViewport - true if any part of the element is visible, false if not.
  • elementWatcher.isFullyInViewport - true if the entire element is visible [1].
  • elementWatcher.isAboveViewport - true if any part of the element is above the viewport.
  • elementWatcher.isBelowViewport - true if any part of the element is below the viewport.
  • elementWatcher.top - distance from the top of the document to the top of this watcher.
  • elementWatcher.bottom - distance from the top of the document to the bottom of this watcher.
  • elementWatcher.height - top - bottom.
  • elementWatcher.watchItem - the element, number, or object that this watcher is watching.
  • elementWatcher.offsets - an object that determines the offsets of this watcher. See "Offsets".
  1. If the element is larger than the viewport isFullyInViewport is true when the element spans the entire viewport.

Methods

  • elementWatcher.on/off/one - the standard event functions.
  • elementWatcher.recalculateLocation - recalculates the location of the element in relation to the document.
  • elementWatcher.destroy - removes this watcher and clears out its event listeners.
  • elementWatcher.lock - locks this watcher at its current location. See "Locking".
  • elementWatcher.unlock - unlocks this watcher.

These methods are automatically called by the scrollMonitor, you should never need them:

  • elementWatcher.update - updates the boolean properties in relation to the viewport. Does not trigger events.
  • elementWatcher.triggerCallbacks - triggers any callbacks that need to be called.

Locking

Sometimes you want to change the element you're watching, but want to continue watching the original area. One common use case is setting position: fixed on an element when it exits the viewport, then removing positioning when it when it reenters.

var watcher = scrollMonitor.create( $element );
watcher.lock(); // ensure that we're always watching the place the element originally was

watcher.exitViewport(function() {
    $element.addClass('fixed');
});
watcher.enterViewport(function() {
    $element.removeClass('fixed');
});

Because the watcher was locked on the second line, the scroll monitor will never recalculate its location.

Offsets

If you want to trigger an event when the edge of an element is near the edge of the viewport, you can use offsets. The offset is the second argument to scrollMonitor.create.

This will trigger events when an element gets within 200px of the viewport:

scrollMonitor.create( element, 200 )

This will trigger when the element is 200px inside the viewport:

scrollMonitor.create( element, -200 )

If you only want it to affect the top and bottom differently you can send an object in.

scrollMonitor.create( element, {top: 200, bottom: 50})

If you only want it to affect the top and not the bottom you can use only one property in.

scrollMonitor.create( element, {top: 200})

scrollMonitor Module

Methods

  • scrollMonitor.createContainer( containerEl ) - returns a new ScrollMonitorContainer that can be used just like the scrollMonitor module.
  • scrollMonitor.create( watchItem, offsets ) - Returns a new watcher. watchItem is a DOM element, jQuery object, NodeList, CSS selector, object with .top and .bottom, or a number.
  • scrollMonitor.update() - update and trigger all watchers.
  • scrollMonitor.recalculateLocations() - recalculate the location of all unlocked watchers and trigger if needed.

Properties

  • scrollMonitor.viewportTop - distance from the top of the document to the top of the viewport.
  • scrollMonitor.viewportBottom - distance from the top of the document to the bottom of the viewport.
  • scrollMonitor.viewportHeight - height of the viewport.
  • scrollMonitor.documentHeight - height of the document.

Contributing

There is a set of unit tests written with Mocha + Chai that run in testem. Getting them running is simple:

npm install
npm test

then open http://localhost:7357

NPM DownloadsLast 30 Days