캐러셀의 모바일 동작에서 사용자 환경을 개선하기 위해 아래와 같이 스와이프 동작을 추가하였다.
let startX;
let startY;
let endX;
let endY;
carouselRefCurrent.addEventListener('touchstart', handleTouchStart, false);
carouselRefCurrent.addEventListener('touchmove', handleTouchMove, false);
carouselRefCurrent.addEventListener('touchend', handleTouchEnd, false);
function handleTouchStart(event) {
startX = event.touches[0].clientX;
startY = event.touches[0].clientY;
if (event.touches.length >= 2) {
startX = NaN;
startY = NaN;
}
}
function handleTouchMove(event) {
endX = event.touches[0].clientX;
endY = event.touches[0].clientY;
const distanceX = endX - startX;
const distanceY = endY - startY;
}
function handleTouchEnd() {
const distanceX = endX - startX;
const distanceY = endY - startY;
newSetCarousel.setCurrentState({
className: 'carousel-controls-previous',
});
newSetCarousel.setCurrentState({
className: 'carousel-controls-next',
});
startX = NaN;
startY = NaN;
endX = NaN;
endY = NaN;
}
// 코드 생략...
스와이프는 잘 동작하였지만, 화면의 높이가 100vh가 넘을 경우 스와이프 동작 시 스크롤이 같이 움직여서 동작이 매끄럽지 않았다. 또한 미세한 X축 움직임에도 스와이드가 동작되어 사용성이 떨어졌다.
아래 코드를 사용하면 위 두 가지 문제를 해결하여 스와이프 동작을 개선할 수 있다.
// 코드 생략...
function handleTouchMove(event) {
endX = event.touches[0].clientX;
endY = event.touches[0].clientY;
const distanceX = endX - startX;
const distanceY = endY - startY;
if (Math.abs(distanceX) > Math.abs(distanceY)) {
event.preventDefault();
}
}
function handleTouchEnd() {
const distanceX = endX - startX;
const distanceY = endY - startY;
if (Math.abs(distanceX) > Math.abs(distanceY) && distanceX > 50) {
newSetCarousel.setCurrentState({
className: 'carousel-controls-previous',
});
} else if (Math.abs(distanceX) > Math.abs(distanceY) && distanceX < -50) {
newSetCarousel.setCurrentState({
className: 'carousel-controls-next',
});
}
startX = NaN;
startY = NaN;
endX = NaN;
endY = NaN;
}
// 코드 생략...
touchmove 이벤트가 발생할 때, Y축 움직임보다 X축 움직임이 더 크면 event.preventDefault를 통해서 이벤트 기본 동작 막아 스와이프 동작시 스크롤 이벤트가 작동되는 문제를 해결할 수 있다.
또한 touch가 시작될 때의 X축 위치와 touch가 끝날 때의 X축 위치의 차이를 계산하여 특정 값 미만인 경우 스와이프가 동작하지 않도록 수정하여 미세한 X축 움직임에도 스와이드가 동작하는 문제를 해결할 수 있다.