Giter Site home page Giter Site logo

scroll-observer's Introduction

Lightweight vanilla javascript library to handle intersection observers

Initializing

import {ScrollObserver} from './src/scroll.observer.js';

const scrollObserver = new ScrollObserver();

In a browser, you can use the UMD files located in the dist directory:

<script src="dist/scroll.observer.umd.js"></script>
const scrollObserver = new ScrollObserver();

Parameters

Basic params

The basic parameters you can specify are the same you'd use with an intersection observer (see https://developer.mozilla.org/fr/docs/Web/API/Intersection_Observer_API):

Parameter Type Default Description
root CSS selector "viewport" Root intersection observer parameter
rootMargin String "0px" Root margins to use
threshold array 0 Array of thresholds that will trigger the callback function
const scrollObserver = new ScrollObserver({
    // root
    root: document.getElementById("content"),
    // rootMargins
    rootMargin: "20px 0",
    // threshold array
    threshold: [0, 0.25, 0.5, 0.75, 1]
});

Observe elements

Once you've created an observer, you need to observe elements.

You can add one or multiple elements to observe thanks to the observe() method:

scrollObserver.observe({
    // elements to observe
    elements: document.querySelectorAll(".scroll-observed-el")
});

You can use a CSS selector instead of a list of elements:

// exactly the same as above
scrollObserver.observe({
    // elements to observe specified with a selector
    selector: ".scroll-observed-el"
});

There are 3 callbacks that you can use when observing an element, onBeforeElVisible(), onElVisible() and onElHidden, trigger by the intersection observer based on the root, rootMargin and threshold parameters:

scrollObserver.observe({
    // elements to observe
    elements: document.querySelectorAll(".scroll-observed-el"),
    // wait for 200ms (cumulative) each time one of this element is visible
    stagger: 200,
    // an ".scroll-observed-el" element became visible
    onBeforeElVisible: (observedEl) => {
        // observedEl is an object containing the original HTML element, its bounding rectangle and other properties
        console.log(observedEl);
    },
    // an ".scroll-observed-el" element became visible and its staggering timeout has run
    onElVisible: (observedEl) => {
        // observedEl is an object containing the original HTML element, its bounding rectangle and other properties
        console.log(observedEl);
    },
    // an ".scroll-observed-el" element became hidden
    onElHidden: (observedEl) => {
        // observedEl is an object containing the original HTML element, its bounding rectangle and other properties
        console.log(observedEl);
    },
});

Complete parameter list

Here is a complete list of all observe() method parameters:

Parameter Type Default Description
elements array of HTML elements [] elements to observe
selector string null elements to observe based on a CSS selector
keepObserving bool false Whether we should keep observing the element after it has been in and out of view
triggerRatio float between 0 and 1 0 The ratio at which the visible/hidden callback should be called
alwaysTrigger bool true Whether it should trigger the visible callback multiple times or just once
stagger float 0 Number of milliseconds to wait before calling the visible callback (used for staggering animations)
onBeforeElVisible function(observedEl) void Function to execute right when this element become visible. Use it to change this element staggering property for example
onElVisible function(observedEl) void Function to execute when this element become visible, after the staggering timeout
onElHidden function(observedEl) void Function to execute when this element become hidden

Unobserve elements

You can decide to stop observing elements whenever you want.

Unobserving one element

You can pass a HTML element to the unobserveEl() method:

scrollObserver.unobserveEl(document.getElementById("observed-el"));

Unobserving multiple elements

You can pass an array of elements to the unobserveEls() method:

scrollObserver.unobserveEls(document.querySelectorAll(".scroll-observed-el"));

Unobserving all elements and disconnect observer

You can also decide to unobserve all elements and disconnect your observer:

scrollObserver.unobserveAll();

Events

There are 4 events you can use, onError(), onBeforeElVisible(), onElVisible() and onElHidden():

scrollObserver.onError(() => {
    // intersection observer API is not supported, do something
}).onBeforeElVisible((observedEl) => {
    // called each time an observed element become visible
    console.log(observedEl);
}).onElVisible((observedEl) => {
    // called each time an observed element become visible but after its staggering timeout
    console.log(observedEl);
}).onElHidden((observedEl) => {
    // called each time an observed element become hidden
    console.log(observedEl);
});

scroll-observer's People

Contributors

martinlaxenaire avatar

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.