When attempting to create an infinite loop for a carousel with a click event on a specific div to center it at a desired position, I encountered an issue. If the clicked item is more than one position away from the center, an unexpected effect occurs that does not follow the usual logic.
I attempted to address this problem by calculating the distance from the center and moving the items one by one accordingly. However, due to the asynchronous nature of animations, the loop doesn't wait for the animations to finish, resulting in the strange effect.
The desired outcome is to achieve an infinite carousel feel where clicking an item five positions away from the center centers it, causing the out-of-view items to slide in from their respective directions to create a loop effect.
Any assistance would be greatly appreciated as I am new to web development. A well-explained solution would be highly valued.
JS:
const serviceList = document.querySelectorAll('.service__block');
serviceList.forEach(service => {
service.addEventListener('click', () => {
markSelectedService(service);
moveService(checkDistance(service));
});
});
//Adds the class to the clicked service
function markSelectedService(service) {
removeSelectedClass();
service.classList.add('selected');
}
//Removes the selected class from all services
function removeSelectedClass() {
serviceList.forEach(service => {
service.classList.remove('selected');
});
}
//Check distance from center
function checkDistance(service) {
let distance = service.dataset.order - 4;
return distance;
}
//Move the service one by one n times
function moveService(distance) {
if (distance > 0) {
for (var i = 0; i < distance; i++) {
serviceList.forEach(service => {
service.dataset.order = parseInt(service.dataset.order) - 1;
if (parseInt(service.dataset.order) === -1) {
service.dataset.order = 11;
}
});
}
} else if (distance < 0) {
distance = distance * -1;
for (var i = 0; i < distance; i++) {
serviceList.forEach(service => {
service.dataset.order = parseInt(service.dataset.order) + 1;
if (parseInt(service.dataset.order) === 12) {
service.dataset.order = 0;
}
});
}
}
}
Link to codepen: https://codepen.io/tomyshoam/pen/yLLLYyQ