I’m using Swiper.js in my React project. It’s in swipeable free mode with autoplay. I will stop the autoplay when touchstart
event is triggered, and resume the autoplay after touchend
.
However, it’ll be awkward if the autoplay resumes immediately after the user release their finger since there’s still momentum velocity caused by the swipe. I wonder if there’s a way to detect the swiper stops, i.e. the velocity equals zero. I think the proper timing to resume autoplay is after the swiper stops for a while.
The following is my current workaround, wait 1 second until resuming the autoplay: (I also purposely slow down the momentum effect)
import React, { useRef, useState, useEffect } from "react";
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";
// Import Swiper styles
import "swiper/css";
import "swiper/css/bundle";
import "swiper/css/free-mode"
import "swiper/css/pagination"
import "./App.css";
// import Swiper core and required modules
import SwiperCore, {
Autoplay,
FreeMode, Pagination
} from 'swiper';
// install Swiper modules
SwiperCore.use([FreeMode, Autoplay, Pagination]);
export default function App() {
const swiperRef = useRef(null);
let disableAutoPlayTimer = null;
useEffect(() => {
const swiper = swiperRef.current;
// subscribe event
swiper.addEventListener("touchstart", touchStartHandler);
swiper.addEventListener("touchend", touchEndHandler);
return () => {
// unsubscribe event
swiper.removeEventListener("touchstart", touchStartHandler);
swiper.removeEventListener("touchend", touchEndHandler);
};
}, []);
const touchStartHandler = (e) => {
swiperRef.current.swiper.autoplay.stop();
}
const touchEndHandler = (e) => {
// I'm now using a timer to wait 1 second for the swiper to stop
if (!disableAutoPlayTimer) {
disableAutoPlayTimer = setTimeout(() => {
swiperRef.current.swiper.autoplay.start();
disableAutoPlayTimer = null;
}, 1000);
}
}
return (
<>
<Swiper
dir="rtl"
slidesPerView="auto"
spaceBetween={30}
freeMode={{
enabled: true,
momentumVelocityRatio: 0.5
}}
loop={true}
loopedSlides={9}
grabCursor={true}
autoplay={{
"delay": 0,
"disableOnInteraction": false
}}
speed={1000}
className="mySwiper"
ref={swiperRef}
>
<SwiperSlide>Slide 1</SwiperSlide>
<SwiperSlide>Slide 2</SwiperSlide>
<SwiperSlide><span style={{color: 'red'}}>Slide 3</span></SwiperSlide>
<SwiperSlide>Slide 4</SwiperSlide>
<SwiperSlide>Slide 5</SwiperSlide>
<SwiperSlide>Slide 6</SwiperSlide>
<SwiperSlide>Slide 7</SwiperSlide>
<SwiperSlide>Slide 8</SwiperSlide>
<SwiperSlide>Slide 9</SwiperSlide>
</Swiper>
</>
)
}
All in all, my question is, “How to know the current velocity of Swiper.js?”, or “How do I know the swiper is not moving?”
Any idea?