Skip to content

Commit

Permalink
Added drag-to-scroll functionality for Testimonials section (#533)
Browse files Browse the repository at this point in the history
  • Loading branch information
Harsh8089 authored Oct 21, 2024
1 parent eb7fdc8 commit facca11
Showing 1 changed file with 72 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/components/ui/infinite-moving-cards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,78 @@ export const InfiniteMovingCards = ({
const containerRef = React.useRef<HTMLDivElement>(null);
const scrollerRef = React.useRef<HTMLUListElement>(null);

const [isDown, setIsDown] = useState<boolean>(false);
const [startX, setStartX] = useState<number>(0.0);
const [scrollLeft, setscrollLeft] = useState<number>(0.0);
const [totalWidth, setTotalWidth] = useState<number>(0.0);

useEffect(() => {
const slider = containerRef.current;
const handleMouseDown = (event: MouseEvent) => {
if (!slider) return;
setIsDown(true);
setStartX(event.pageX - slider.offsetLeft);
setscrollLeft(slider.scrollLeft);
};

const handleMouseMove = (event: MouseEvent) => {
if (slider && isDown) {
const x = event.pageX - slider.offsetLeft;
const walk = x - startX;
const newScrollLeft = scrollLeft - walk;

const maxScrollLeft = totalWidth - slider.clientWidth;

if (newScrollLeft < 0) slider.scrollLeft = 0;
else if (newScrollLeft > maxScrollLeft)
slider.scrollLeft = maxScrollLeft;
else slider.scrollLeft = newScrollLeft;
}
};

const handleMouseLeave = () => {
setIsDown(false);
};

const handleMouseUp = () => {
setIsDown(false);
};

if (slider) {
slider.addEventListener('mousedown', handleMouseDown);
slider.addEventListener('mousemove', handleMouseMove);
slider.addEventListener('mouseleave', handleMouseLeave);
slider.addEventListener('mouseup', handleMouseUp);
}

return () => {
if (slider) {
slider.removeEventListener('mousedown', handleMouseDown);
slider.removeEventListener('mousemove', handleMouseMove);
slider.removeEventListener('mouseleave', handleMouseLeave);
slider.removeEventListener('mouseup', handleMouseMove);
}
};
}, [isDown, startX, scrollLeft]);

useEffect(() => {
addAnimation();
const scroller = scrollerRef.current;
if (scroller) {
const listItems = scroller.querySelectorAll('li');
let width = 0,
length = 0;
listItems.forEach((item) => {
if (length < listItems.length / 2)
width +=
(item as HTMLElement).offsetWidth +
parseFloat(getComputedStyle(item).marginRight);
length++;
});
setTotalWidth(width);
}
}, []);

const [start, setStart] = useState(false);
function addAnimation() {
if (containerRef.current && scrollerRef.current) {
Expand Down Expand Up @@ -64,6 +133,9 @@ export const InfiniteMovingCards = ({
'scroller relative z-20 max-w-7xl overflow-hidden [mask-image:linear-gradient(to_right,transparent,white_20%,white_80%,transparent)]',
className
)}
style={{
userSelect: 'none',
}}
>
<ul
ref={scrollerRef}
Expand Down

0 comments on commit facca11

Please sign in to comment.