1. Help Centre
  2. Getting Started

Scroll events

Data from page Scroll events can be accessed via the adnami API, and used to power transitions and animations. The scroll event is attached to a callback function like this:

__adnamiAdsAPI.v1.scrollObserver.addListener(callback);

The callback function returns two parameters, the second ‘payload’ object contains the event data.


addListener(callback: (eventType, payload) => void) : string) : string;

Used in a banner format to listen for scroll events.

Sets up a listener and returns a listener handle.

Throws an exception if removeAllListeners() has been called and is still executing.


The payload object contains the following data:


Property

Type

Description

elementScrolledPercentage

number

A value (between 0 and 100) of the ads scroll completion, as a percentage. The value will be 0 before the ad has scrolled into view, and is 100 once the ad has fully scrolled out of view.

elementScrolledPixels

number

The distance in pixels that the page has been scrolled since the banner came into view.

isInView

boolean

Is true if any part of the banner is visible within the viewport, otherwise is false.

pageScrolledPixels

number

The total distance in pixels that the page has been scrolled.


Below is an example of implementation, showing how the data from the scroll event can be accessed and utilised.

 

const banner = document.getElementById("banner"),

bg = document.getElementById("bg"),

image = document.getElementById("image");




let offline = false, animationStarted = false;




function initialiseScrollObserver(){

try{

if(__adnamiAdsAPI){

__adnamiAdsAPI.v1.scrollObserver.addListener(scrollLogger);

}

}catch{

// Simulate the scroll behaviour when testing offline

offline = true;

console.log("offline mode");

const body = document.body;

gsap.set(body,{height:"200vh"});

gsap.set(banner,{position:"sticky", height:"100vh", top:0});

window.addEventListener("scroll", scrollLogger);

}

}




function scrollLogger(eventType, payload){

let percentageScrolled;

if(!offline){

if(payload.isInView){

triggerAnimation()

percentageScrolled = payload.elementScrolledPercentage;

scrollAnimation(percentageScrolled);

}else{

animationStarted = false;

}

}else{

triggerAnimation();

const scrollTop = eventType.path[0].scrollingElement.scrollTop,

scrollHeight = document.body.offsetHeight/2,

percentageScrolled = gsap.utils.clamp(0, 100, (scrollTop / scrollHeight) * 100);

scrollAnimation(percentageScrolled);

}

}




function triggerAnimation(){

if(!animationStarted){

animationStarted = true;

startAnimation();

}

}




function scrollAnimation(scrollPercent){




// Animation using scroll data

gsap.set(image, {yPercent:100-scrollPercent});

}




function startAnimation(){




// Animation for when banner comes into view

gsap.fromTo(bg, 5, {scale:1},{scale:1.2});

}




initialiseScrollObserver();