javascriptclojurescriptre-frame

Implementing js script for scrolling to a target in Clojurescrip - Re-frame


I'm working on a Clojure project, using clojure, clojurescript, re-frame and reagent. There is a button that I want when it is clicked, the user jumps to the related image tag by scrolling. There are lots of buttons that each button should scroll the screen to the target picture.

As I'm new to clojure world, I don't know how to implement the js script into the project. I have created a button on the views.cljs file with dispatch to the events. But where should I implement the js part? As I've found, it must be in the events.cljs file, but if it's correct, I don't know how to implement that.

Please help me with this code. How should the js code looks like when it's going to be implemented in clojurescript? Thank you in advance.

In views.cljs:

[:button {:on-click #(rf/dispatch [::events/img-one])}]


Solution

  • You're probably looking for Element.scrollIntoView(). I also don't think you have to modify events.cljs, just add this code into views.cljs (I also added some images for testing):

    [:button {:on-click #(.scrollIntoView
                                       (.getElementById js/document "id3"))}
                 "Click me"]
    
    [:div
      [:div [:img#id1 {:src "" :style {:width 600 :height 1000 :background "red"}}]]
      [:div [:img#id2 {:src "" :style {:width 600 :height 1000 :background "pink"}}]]
      [:div [:img#id3 {:src "" :style {:width 600 :height 1000 :background "yellow"}}]]
    

    With argument behavior, scrolling can be smooth:

    [:button {:on-click #(.scrollIntoView
                                       (.getElementById js/document "id3")
                                       (js-obj "behavior" "smooth"))}
                 "Click me"]