const container = document.querySelector('.product-filter-horizontalscroll');
document.querySelectorAll('.wpgb-select').forEach(select => {
select.addEventListener('focus', (event) => {
const selectBox = event.target.getBoundingClientRect();
const containerBox = container.getBoundingClientRect();
// Check if the select box is partially or fully outside the container's viewport
const isOutOfViewport = selectBox.left < containerBox.left || selectBox.right > containerBox.right;
if (isOutOfViewport) {
// Calculate the scroll amount to bring the select into view
const offset = selectBox.left - containerBox.left - (containerBox.width / 2) + (selectBox.width / 2);
// Scroll the container to the left by the offset amount
container.scrollBy({
left: offset,
behavior: 'smooth'
});
}
// Add the focused class after ensuring the element is visible
event.target.classList.add('wpgb-select-focused');
});
select.addEventListener('blur', (event) => {
// Remove the focused class on blur
event.target.classList.remove('wpgb-select-focused');
});
});
// Watch for the dropdown showing
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.type === 'attributes' && mutation.target.classList.contains('wpgb-select-dropdown')) {
const dropdownBox = mutation.target.getBoundingClientRect();
const containerBox = container.getBoundingClientRect();
// Check if dropdown is partially or fully outside the container's viewport
const isOutOfViewport = dropdownBox.left < containerBox.left || dropdownBox.right > containerBox.right;
if (isOutOfViewport) {
// Calculate the scroll amount to bring the dropdown into view
const offset = dropdownBox.left - containerBox.left - (containerBox.width / 2) + (dropdownBox.width / 2);
// Scroll the container to the left by the offset amount
container.scrollBy({
left: offset,
behavior: 'smooth'
});
}
}
});
});
// Start observing changes in attributes for dropdown elements
const dropdown = document.querySelector('.wpgb-select-dropdown');
if (dropdown) {
observer.observe(dropdown, { attributes: true });
}