var loader = document.getElementsByClassName('eye-icon');
var itemimg = document.getElementsByClassName('item-img');
for(var j = 0; j < itemimg.length; j++){
for(var i = 0; i < loader.length; i++){
var animation = bodymovin.loadAnimation({
wrapper: loader[i],
renderer: 'svg',
loop: true,
autoplay: false,
prerender: true,
path: 'js/icon/eye-icon/'
})
itemimg[i].addEventListener("mouseenter", function playAni() {
animation.play();
});
itemimg[i].addEventListener("mouseleave", function stopAni() {
animation.stop();
});
console.log(loader[i]);
}}
If autoplay is true I can see all the animations but all the mouse events do not work. If i enable autoplay to false. I hover any itemimg class only work in the last class... even if i hover the first itemimg, second or third.
that's because of how javascript works.
By the time the event "mouseenter" fires, the animation variable is pointing to the last item in the loop.
You need to scope each instance so it works pointing to the correct instance.
I understood what you say but I am just a beginner in the coding world... Where can i find an example for this?. Thank you!
Still can't figure it out.
can you create a codepen I can check so I can try to help you?
https://codepen.io/lvasquezvega/pen/eGQWrO
thank you in advance!
try this:
````javascript
var loader = document.getElementsByClassName("eye-icon");
function loadBMAnimation(loader) {
var animation = bodymovin.loadAnimation({
container: loader,
renderer: "svg",
loop: true,
autoplay: false,
path: "https://raw.githubusercontent.com/lvasquezvega/bdm/002802718a10c3b86a505385684f92f909968a55/eye-icon.json"
});
loader.addEventListener("mouseenter", function() {
animation.play();
});
loader.addEventListener("mouseleave", function() {
animation.stop();
});
}
for (var i = 0; i < loader.length; i++) {
loadBMAnimation(loader[i]);
}
````
Thank you so much!! It works now!
Most helpful comment
try this:
````javascript
var loader = document.getElementsByClassName("eye-icon");
function loadBMAnimation(loader) {
var animation = bodymovin.loadAnimation({
container: loader,
renderer: "svg",
loop: true,
autoplay: false,
path: "https://raw.githubusercontent.com/lvasquezvega/bdm/002802718a10c3b86a505385684f92f909968a55/eye-icon.json"
});
loader.addEventListener("mouseenter", function() {
animation.play();
});
loader.addEventListener("mouseleave", function() {
animation.stop();
});
}
for (var i = 0; i < loader.length; i++) {
loadBMAnimation(loader[i]);
}
````