I have created a product carousel using Javascript, the idea is i have a row of 10 products and one product is focused means the product i click on it zooms in and show more information about it and it should be in the middle. now when i click on unfocused product whether right or left am expecting that all products shifts until the one i cliked takes the middle position here is the carousel photo:
and this is the Js code:
jQuery(document).ready(function($) {
const carousel = $('.carousel-custom');
const items = $('.carousel-item');
let focusedIndex = 5; // Start with the fourth item focused
// Function to center the focused item
function centerItem(index) {
const item = $(items[index]);
const carouselWidth = carousel.width();
const itemWidth = item.outerWidth(true);
// Calculate the scroll position to center the item
const scrollPosition = 135;
// Debugging output
console.log('Focused Index:', index);
console.log('Item Position:', item.position().left);
console.log('Carousel Width:', carouselWidth);
console.log('Item Width:', itemWidth);
console.log('Scroll Position:', scrollPosition);
// Ensure scroll position is not negative or out of bounds
if (scrollPosition < 0) {
carousel.animate({ scrollLeft: 0 }, 300);
} else if (scrollPosition + carouselWidth > carousel[0].scrollWidth) {
carousel.animate({ scrollLeft: carousel[0].scrollWidth - carouselWidth }, 300);
} else {
// Animate the scroll to the calculated position
carousel.animate({ scrollLeft: scrollPosition }, 300);
}
}
// Function to set the focus on an item by index
function setFocus(index) {
// Remove focused class from all items
items.removeClass('focused');
// Add focused class to the specified item
$(items[index]).addClass('focused');
// Center the focused item
centerItem(index);
}
// Function to trigger a click on the focused item
function triggerClick(index) {
items.eq(index).trigger('click');
}
// Set initial focus on the third item and trigger a click
setFocus(focusedIndex);
triggerClick(focusedIndex); // This simulates a click on the third item
// Click event for carousel items
items.on('click', function() {
const clickedIndex = $(this).index();
console.log('Clicked Index:', clickedIndex); // Debugging output
setFocus(clickedIndex); // Focus on clicked item
});
});
The issue is the products are not shifting when i click on one they stay in the same place.