I'm using reagent to develop a site. It's unclear to me how to work with touch events in reagent, actually, in general. I read this post clojurescript: touch events and Domina, but do i need to use domina to handle on-touch-start events with reagent ? Would anyone have a snippet of code to detect -- given a dom element -- if a user has swiped a % left or right ?
Reagent uses React's virtual DOM and synthetic events. Touch events are available in React but you have to call (.initializeTouchEvents js/React true)
before rendering any component (i.e. before calling reagent.core/render-component
).
Edit: the code below won't work because touch events are more complex than mouse events. See this MDN page for some (JS) examples. React seems to implement the same touch API.
For the swipe percentage, do something like the following (untested):
(defn swipe-element []
(let [swipe-state (atom {:width 0, :start-x 0, :current-x 0})]
(fn []
[:div {:on-touch-start
(fn [e]
(reset! swipe-state {:width (.. e -target -offsetWidth)
:start-x (.. e -target -pageX)
:current-x (.. e -target -pageX)}))
:on-touch-move
(fn [e]
(swap! swipe-state assoc :current-x (.. e -target -pageX)))}
(let [{:keys [width start-x current-x]} @swipe-state
direction (if (> current-x start-x) "right" "left")]
(str "Swipe " direction ": "
(* (/ (.abs js/Math (- start-x current-x)) width) 100) "%")))))