Im doing carousel and suddenly addEventListener(‘animationend’, function(){}) running twice. I placed console.log to view "currentItem", and at the third time it running twice. Where is my mistake?
https://codepen.io/sundozer/pen/VwxENKw
squares[currentItem].addEventListener('animationend', function(){
console.log(currentItem)
squares[currentItem].classList.remove('toLeft')
squares[((currentItem+1)+squares.length) % squares.length].classList.remove('fromRight')
squares[currentItem].classList.add('hide')
changeCurrentItem(currentItem+1)
>Solution :
In your example, whenever you click the button you are running a function which adds new event listeners. If you do not remove the event listeners then they will begin to stack. You can deal with this by saving a reference to the function you add and removing them after. I have fixed your codepen with the following code:
const butR = document.querySelector('.butR')
const squareRed = document.querySelector('.squareRed')
const squarePink = document.querySelector('.squarePink')
const squareBlue = document.querySelector('.squareBlue')
const squares = document.querySelectorAll('.squares')
const container = document.querySelectorAll('.container')
let currentItem = 1;
let enable = 1;
const changeCurrentItem = (number) => {
currentItem = number % squares.length;
}
butR.addEventListener('click', function(){
if (enable === 1) {
squares[currentItem].classList.add('toLeft');
squares[((currentItem+1)+squares.length) % squares.length].classList.add('fromRight');
squares[((currentItem+1)+squares.length) % squares.length].classList.remove('hide');
const animStart = function() {
enable = 0;
}
const animEnd = function() {
enable = 1;
console.log(currentItem);
squares[currentItem].classList.remove('toLeft');
squares[((currentItem+1)+squares.length) % squares.length].classList.remove('fromRight');
squares[currentItem].classList.add('hide');
squares[currentItem].removeEventListener('animationstart', animStart);
squares[currentItem].removeEventListener('animationend', animEnd);
changeCurrentItem(currentItem+1);
}
squares[currentItem].addEventListener('animationstart', animStart);
squares[currentItem].addEventListener('animationend', animEnd);
}
})