I’m facing a challenge with dynamically setting the stage of a Lottie upon the DOM content being fully loaded. My goal is to randomly select a Lottie and a specific stage in it, and then display the animation starting from the selected stage. However, despite my efforts, the animation does not start from any stage. Any insights into resolving this issue would be greatly appreciated.
Here is my code:
document.addEventListener("DOMContentLoaded", function () {
// List of the Lotties
var lottieFiles = [
{
path: 'lottie1.json',
stages: [
{ from: 0, to: 50 },
{ from: 51, to: 100 },
{ from: 101, to: 150 },
{ from: 151, to: 200 }
]
},
{
path: 'lottie2.json',
stages: [
{ from: 0, to: 60 },
{ from: 61, to: 120 },
{ from: 121, to: 180 },
{ from: 181, to: 240 }
]
},
{
path: 'lottie3.json',
stages: [
{ from: 0, to: 40 },
{ from: 41, to: 80 },
{ from: 81, to: 120 },
{ from: 121, to: 160 }
]
},
{
path: 'lottie4.json',
stages: [
{ from: 0, to: 70 },
{ from: 71, to: 140 },
{ from: 141, to: 210 },
{ from: 211, to: 280 }
]
}
];
// Choose random Lottie
var randomIndex = Math.floor(Math.random() * lottieFiles.length);
var selectedLottie = lottieFiles[randomIndex];
// Choose random stage
var randomStageIndex = Math.floor(Math.random() * selectedLottie.stages.length);
var selectedStage = selectedLottie.stages[randomStageIndex];
// Load the selected Lottie from it's stage
var animation = lottie.loadAnimation({
container: document.getElementById('lottie-animation'),
renderer: 'svg',
loop: true,
autoplay: true,
path: selectedLottie.path
});
animation.goToAndStop(randomStageIndex.from, true);
});
I was trying to solve the issue by refining the stage selection logic. I revisited the script and adjusted how it identifies and sets the animation stage. Specifically, I made changes to directly specify the stage for the animation without relying on a random index. However, it still shows up at the wrong stage.