dom-watcher

register callbacks to fire when DOM elements enter/leave browser viewport

Usage no npm install needed!

<script type="module">
  import domWatcher from 'https://cdn.skypack.dev/dom-watcher';
</script>

README

dom-watcher

Small library that lets you register callbacks for when your DOM elements enter or leave browser viewport area. Useful for revealing animation effects

source: https://github.com/asgmax/dom-watcher

Import and initialization

import { Watcher } from "dom-watcher";

let watcher = new Watcher({});

you can also pass default parameters to be applied to every watched element


let watcher = new Watcher({
    defaultParams: {
        fraction: 0.6,
        repeated: true
    }
});

fraction: number(0...1) - specifies percentage of a DOM elemet to be revealed before callback triggers. Set 0 to trigger callback as soon as element enters viewport, at 0.5 callback will fire only after at least 50% of the element was revealed. At 1 callback will trigger only after the element is completely inside the viewport

repeated: boolean - defines whether or not should callback trigger if element keeps continuously re-entering viewport. Default value is false which means callback will only trigger once per page load

onHide: function(element) - function to be called when element leaves viewport area

Adding watched elements

watcher.add(element, callback, options?)

element: can be DOM element (or array) as well as any jQuery element

callback: function to be called when the element enters viewport. Will receive DOM element as its only parameter. Will fire separately for each element if first parameter was array or jQuery element

options: optional parameter, will override defaultParams used while creating Watcher instance

Examples

watcher.add(
    $(".container"),
    (el) => {
        // this callback will be triggered when element(s) enters viewport
    },
    {
        onHide: function(el) {
            // this callback will be triggered when element leaves viewport
        },
        fraction: 0, // custom fraction value
        repeated: true // callback will be firing each time any of .container elements enter viewport
    }
);

simple slide-in reveal using gsap

watcher.add(
    document.getElementById("pic"),
    (el) => {
        TweenMax.fromTo(el, 1, {x: -300, opacity: 0}, {x: 0, opacity: 1})
    }
);