website/assets/scripts/carousel.js

96 lines
3.4 KiB
JavaScript

function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
);
}
//
// little addon to enhance the carousel
var carousels = document.querySelectorAll('.carousel');
// first addon to change "enabled" slide indicator (way to complicated)
Array.from(carousels).forEach((carousel) => {
let viewport = carousel.getElementsByClassName("carousel__viewport")[0];
let slides = carousel.getElementsByClassName("carousel__slide");
let nav_items = Array.from(carousel.getElementsByClassName("carousel__navigation-item"))
let last_scroll_pos = null;
viewport.onscroll = (_event) => {
let position = Math.ceil(slides.length * viewport.scrollLeft / viewport.scrollWidth);
let direction = last_scroll_pos == null || last_scroll_pos < viewport.scrollLeft;
console.log("direction", direction);
console.log("position", position);
last_scroll_pos = viewport.scrollLeft;
nav_items.forEach((item, index) => {
if (
(direction && position > index-1 && position <= index) ||
(!direction && position >= index && position < index+1)
) {
if (!item.classList.contains("enabled")) {
item.classList.add("enabled")
}
return
}
if (item.classList.contains("enabled")) {
item.classList.remove("enabled")
}
})
}
})
// second addon to replace the anchor with javascript managed jump scroll
// Iterate through each 'carousel__viewport' element
carousels.forEach(function(carousel) {
var viewport = carousel.querySelector('.carousel__viewport')
// Get all elements with the class 'carousel__slide' within the current 'carousel__viewport'
var slides = viewport.querySelectorAll('.carousel__slide');
var prevButtons = viewport.querySelectorAll('.carousel__prev');
var nextButtons = viewport.querySelectorAll('.carousel__next');
var navigationButtons = carousel.querySelectorAll('.carousel__navigation-button');
console.log(prevButtons)
console.log(navigationButtons)
prevButtons.forEach(function(prevButton, index) {
// remove href, for css only carousel
prevButton.removeAttribute('href');
prevButton.addEventListener('click', function() {
console.log("Click of previous", index)
if (index == 0) {
viewport.scrollLeft = slides.length * slides[0].offsetWidth;
return;
}
viewport.scrollLeft -= slides[0].offsetWidth;
});
});
nextButtons.forEach(function(nextButton, index) {
nextButton.removeAttribute('href');
nextButton.addEventListener('click', function() {
if (index == slides.length-1) {
viewport.scrollLeft = 0;
return;
}
viewport.scrollLeft += slides[0].offsetWidth;
});
});
navigationButtons.forEach(function(btn, index) {
btn.removeAttribute('href');
btn.addEventListener('click', function() {
viewport.scrollLeft = slides[0].offsetWidth * index;
});
});
});