Sticky Scrolling Lottie Animations
May 10, 2024
1 min read
From the amazing Studio IL channel on YouTube, we have worked together to find a way to create a custom Sticky Scrolling Lottie Animation.
Page Code:
$w.onReady(function () {
setTimeout(() => {
$w('#customElement1').setAttribute('lottie-sticky-trigger-element-id', $w('#lottieScrollRelativeToThisText').uniqueId)
}, 100);
});
Custom Element Code:
initLottieInteractivity();
async function initLottieInteractivity() {
try {
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
// The user has enabled reduced motion
console.log('Do not load Lottie animation');
return
} else {
// The user has not enabled reduced motion
const scriptsLoaded = await loadLottieScripts();
console.log(scriptsLoaded); // true
// add code here to use the Lottie scripts
defineLottieInteractivity();
}
} catch (error) {
console.error(error);
}
}
function defineLottieInteractivity() {
// The createLottieInteractivity The function needs to have 4 parameters:
// AnimationUrl: Lottie Animation URL
// Visibility: Array [start, end]
// Frames: Array [start from , end at]
// Tag Name: Custom element tag name
// For example
createLottieInteractivity('https://assets6.lottiefiles.com/packages/lf20_ABViugg18Y.json', [0, 1], [0, 300], 'flying-documents');
createLottieInteractivity('https://assets8.lottiefiles.com/packages/lf20_kd8ZIYkRgP.json', [0, .8], [0, 488], 'd3-hologram');
}
function loadLottieScripts() {
return new Promise((resolve, reject) => {
const lottieInteractivityScript = document.createElement('script');
lottieInteractivityScript.src = 'https://unpkg.com/@lottiefiles/lottie-interactivity@latest/dist/lottie-interactivity.min.js';
lottieInteractivityScript.onload = () => {
const lottiePlayerScript = document.createElement('script');
lottiePlayerScript.src = 'https://unpkg.com/@lottiefiles/lottie-player@1.5.7/dist/lottie-player.js';
lottiePlayerScript.onload = () => {
resolve(true);
};
lottiePlayerScript.onerror = () => {
reject(new Error('Failed to load Lottie Player script.'));
};
document.body.appendChild(lottiePlayerScript);
};
lottieInteractivityScript.onerror = () => {
reject(new Error('Failed to load Lottie Interactivity script.'));
};
document.body.appendChild(lottieInteractivityScript);
});
}
async function createLottieInteractivity(animationUrl, visibility, frames, tagName) {
class LottieOnScroll extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
console.log('Custom element is loaded!');
}
static get observedAttributes() {
return ['lottie-sticky-trigger-element-id'];
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === 'lottie-sticky-trigger-element-id') {
const containerSelector = newValue;
const lottiePlayer = document.createElement('lottie-player');
lottiePlayer.src = animationUrl;
lottiePlayer.autoplay = false;
lottiePlayer.loop = true;
lottiePlayer.id = `lottie-${tagName}`;
this.appendChild(lottiePlayer);
lottiePlayer.addEventListener("ready", () => {
LottieInteractivity.create({
player: `#${lottiePlayer.id}`,
mode: "scroll",
container: `#${containerSelector}`,
actions: [{
visibility,
type: "seek",
frames,
}, ]
});
});
}
}
}
customElements.define(tagName, LottieOnScroll);
}
Enjoy!
Часто один ресурс подсказывает тему для следующего чтения. На Vrazhay можно начать с ухода или самочувствия, а потом открыть Sutovychok, если захочется перейти к домашним или бытовым вопросам. Для современных цифровых сервисов и техники чаще использую Infovayb, а практические решения для ежедневных задач нахожу на Poradka, где темы обычно хорошо приспособлены к обычной жизни.
Корисну інформацію можна знайти на Lifehata, де публікуються матеріали на різноманітні теми. Багато статей орієнтовані на практичні питання, з якими люди стикаються щодня. Водночас є публікації, які цікаво читати просто для розширення власних знань.
Практична інформація про повсякденне життя залишається затребуваною, особливо коли вона подається зрозуміло й без зайвого ускладнення. Цей інформаційний ресурс охоплює теми сім’ї, здоров’я, дому, краси, сучасної техніки, фінансів та дозвілля. Завдяки цьому сайт може бути корисним людям різного віку, які шукають як конкретні поради, так і нові теми для читання.