Browse Source

onTouchEnd for mobile, onScroll with timeout for desktop

Ivan Asmer 3 years ago
parent
commit
6e5eddd089
1 changed files with 17 additions and 2 deletions
  1. 17 2
      src/index.js

+ 17 - 2
src/index.js

@@ -4,6 +4,7 @@ export const SliderImage = ({images = [], className, onChange, onClick, ...props
     const divRef                = useRef()
     const divRef                = useRef()
     const containerRef          = useRef()
     const containerRef          = useRef()
     const autoscroll            = useRef(false)
     const autoscroll            = useRef(false)
+    const inTouch               = useRef(false)
     const timeout               = useRef(false)
     const timeout               = useRef(false)
 
 
     const [imgs, setImgs]       = useState([])
     const [imgs, setImgs]       = useState([])
@@ -45,6 +46,13 @@ export const SliderImage = ({images = [], className, onChange, onClick, ...props
     }
     }
 
 
     const onTouchEnd = () => {
     const onTouchEnd = () => {
+        if (inTouch.current){
+            if (timeout.current) clearInterval(timeout.current)
+
+            timeout.current = setTimeout(onTouchEnd, 200)
+            return;
+        }
+
         const {scrollLeft, scrollWidth} = containerRef.current;
         const {scrollLeft, scrollWidth} = containerRef.current;
         const viewPortWidth             = containerRef.current.getBoundingClientRect().width
         const viewPortWidth             = containerRef.current.getBoundingClientRect().width
 
 
@@ -127,9 +135,16 @@ export const SliderImage = ({images = [], className, onChange, onClick, ...props
     return (
     return (
         <div className={className} 
         <div className={className} 
              style={{cssText: `overflow: auto; -ms-overflow-style: none; scrollbar-width: none`}}
              style={{cssText: `overflow: auto; -ms-overflow-style: none; scrollbar-width: none`}}
-             //onScroll={onScroll} //TODO: do it only on desktop, on touch devices use onTouchEnd
+             onScroll={onScroll} //TODO: do it only on desktop, on touch devices use onTouchEnd
              ref={containerRef} 
              ref={containerRef} 
-             {...(isTouchDevice() ? {onTouchEnd} : {onScroll})}
+            {...isTouchDevice() ? {
+                onTouchStart(){
+                    inTouch.current = true
+                },
+                onTouchEnd(){
+                    inTouch.current = false
+                }
+            }: {}}
             >
             >
             <div ref={divRef}>
             <div ref={divRef}>
                 {images.map((image, i) => <img  src={image} 
                 {images.map((image, i) => <img  src={image}