Jump to an example:

Enter/Leave Viewport Example

This example shows how to perform an action when a tracked element enters and leaves the viewport.

import scrollTracker from "DEGJS/scrollTracker";
import eventAggregator from "DEGJS/eventAggregator";

eventAggregator.subscribe('scrollTracker.elementInViewportChange', 
	onElementInViewportChange);

let elToTrack = document.querySelector('#example1-tracked-el');
let scrollTrackerInst = scrollTracker();

scrollTrackerInst.trackElement(elToTrack);

function onElementInViewportChange(e) {
	if(e.isInViewport) {
		document.body.classList.add('blue');
	} else {
		document.body.classList.remove('blue');
	}
}

Now, scroll down the page to bring the tracked element into the viewport.

Tracked element

Offset Example

This example shows how to apply an offset in conjunction with a tracked element entering and leaving the viewport.

import scrollTracker from "DEGJS/scrollTracker";
import eventAggregator from "DEGJS/eventAggregator";

eventAggregator.subscribe('scrollTracker.elementInViewportChange', 
	onElementInViewportChange);

let elToTrack = document.querySelector('#example2-tracked-el');
let scrollTrackerInst = scrollTracker();

scrollTrackerInst.trackElement(elToTrack,
	{
		offset: {
			top: "50%",
			bottom: "50%"
		}
	}
);

function onElementInViewportChange(e) {
	if(e.isInViewport) {
		document.body.classList.add('blue');
	} else {
		document.body.classList.remove('blue');
	}
}

Now, scroll down the page to bring the tracked element into the viewport.

Tracked element

Scroll Event Example

This example shows how to perform an action when a scroll event occurs while a tracked element is within the viewport.

import scrollTracker from "DEGJS/scrollTracker";
import eventAggregator from "DEGJS/eventAggregator";

eventAggregator.subscribe('scrollTracker.elementScroll', 
	onElementScroll);

let elToTrack = document.querySelector('#example3-tracked-el');
let scrollTrackerInst = scrollTracker();

scrollTrackerInst.trackElement(elToTrack,
	{
		publishScrollEvents: "inViewportOnly"
	}
);

function onElementScroll(e) {
	let ratio = e.rect.top / document.documentElement.clientHeight;
	let opacity = ratio > .5 ? 1 - ratio : ratio * 2;
	e.element.style.opacity = opacity;
}

Now, scroll down the page to bring the tracked element into the viewport.

Tracked element