website/assets/scripts/carousel.js

44 lines
1.5 KiB
JavaScript
Raw Normal View History

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
Array.from(document.getElementsByClassName("carousel")).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 = slides.length * viewport.scrollLeft / viewport.scrollWidth;
let direction = last_scroll_pos == null || last_scroll_pos < viewport.scrollLeft;
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")
}
})
}
})