53 lines
1.5 KiB
JavaScript
53 lines
1.5 KiB
JavaScript
const carouselTrack = document.querySelector('.gallery__track');
|
|
const prevArrow = document.querySelector('.gallery__arrow--prev');
|
|
const nextArrow = document.querySelector('.gallery__arrow--next');
|
|
|
|
if (carouselTrack) {
|
|
const items = Array.from(carouselTrack.querySelectorAll('.gallery__item'));
|
|
const getItemsPerPage = () => (window.matchMedia('(max-width: 900px)').matches ? 1 : 3);
|
|
let itemsPerPage = getItemsPerPage();
|
|
const pageCount = Math.ceil(items.length / itemsPerPage);
|
|
let activePage = 0;
|
|
|
|
function scrollToPage(page) {
|
|
activePage = page;
|
|
const pageWidth = carouselTrack.clientWidth;
|
|
carouselTrack.scrollTo({ left: pageWidth * page, behavior: 'smooth' });
|
|
}
|
|
|
|
function showNext() {
|
|
activePage = (activePage + 1) % pageCount;
|
|
scrollToPage(activePage);
|
|
}
|
|
|
|
function showPrev() {
|
|
activePage = (activePage - 1 + pageCount) % pageCount;
|
|
scrollToPage(activePage);
|
|
}
|
|
|
|
function refreshCarousel() {
|
|
const responsiveItemsPerPage = getItemsPerPage();
|
|
if (responsiveItemsPerPage !== itemsPerPage) {
|
|
itemsPerPage = responsiveItemsPerPage;
|
|
window.location.reload();
|
|
}
|
|
}
|
|
|
|
if (nextArrow) nextArrow.addEventListener('click', showNext);
|
|
if (prevArrow) prevArrow.addEventListener('click', showPrev);
|
|
|
|
document.addEventListener('keydown', (event) => {
|
|
if (event.key === 'ArrowRight') {
|
|
showNext();
|
|
}
|
|
if (event.key === 'ArrowLeft') {
|
|
showPrev();
|
|
}
|
|
});
|
|
|
|
window.addEventListener('resize', () => {
|
|
refreshCarousel();
|
|
scrollToPage(activePage);
|
|
});
|
|
}
|