I'm trying to target a random element on each loop of a keyframed anime.js animation.
Looking at the documentation, I can see that there is a loopComplete callback function. So, I created a function to assign a random child element to the variable random_target.
While I can see in the console log that the value of random_target is changing, the anime.js loop continues to target the first-generated random_target.
How can I ensure that the animation re-targets on loop completion?
var pulseTargets = document.querySelector(".pulse-parent").children;
var random_target = null;
function getRandomTarget() {
random_target = pulseTargets[Math.floor(Math.random() * pulseTargets.length)];
}
getRandomTarget();
console.log(random_target);
anime({
targets: random_target,
keyframes: [{
opacity: 1
}, {
opacity: 0.3
}, {
opacity: 1
}],
duration: 3000,
loop: true,
loopComplete: function(anim) {
getRandomTarget();
console.log(random_target)
}
});
.even\:font-light> :nth-child(even) {
font-weight: 300;
}
.odd\:font-black> :nth-child(odd) {
font-weight: 900;
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
</head>
<body>
<div class="container col-span-full mx-auto h-auto relative mt-32 pb-16">
<div class="grid grid-cols-1 md:grid-cols-3">
<div class="pulse-parent block font-sans odd:font-black tracking-widest even:font-light text-amber-400 col-span-1 h-[6em] overflow-hidden -mt-4 text-justify" style="text-justify: inter-character">
<span>CHILD1</span> <span>CHILD2</span> <span>CHILD3</span> <span>CHILD4</span> <span>CHILD5</span>
</div>
</div>
</div>
</body>
</html>
After digging into the anim object supplied to the callback function, I was able to figure this out. I needed to update a few targets on the animation object, because once initialized the animation doesn't look for an updated target value.
var pulseTargets = document.querySelector('.pulse-parent').children
var random_target = null
function getRandomTarget() {
random_target = pulseTargets[Math.floor(Math.random() * pulseTargets.length)]
}
getRandomTarget()
console.log(random_target)
anime({
targets: random_target,
keyframes: [
{opacity: 1},
{opacity: 0.3},
{opacity: 1}
],
duration: 3000,
loop: true,
loopComplete: function (anim) {
getRandomTarget();
anim.targets = random_target;
anim.animatables[0].target = random_target;
anim.animations[0].animatable.target = random_target;
}
})
I'm not sure if this is the best way to do it, but it works for me.