Skip to content

Instantly share code, notes, and snippets.

@jasich
Created December 11, 2016 02:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasich/21ab25db923e85e1252bed13cf65f0d8 to your computer and use it in GitHub Desktop.
Save jasich/21ab25db923e85e1252bed13cf65f0d8 to your computer and use it in GitHub Desktop.
ClojureScript scroll element into view
;; Based on https://github.com/GabrielDelepine/smooth-scroll/blob/main/smooth-scroll.js
(ns example.scroll)
(def speed 500)
(def moving-frequency 15)
(defn cur-doc-top []
(+ (.. js/document -body -scrollTop) (.. js/document -documentElement -scrollTop)))
(defn element-top [elem top]
(if (.-offsetParent elem)
(let [client-top (or (.-clientTop elem) 0)
offset-top (.-offsetTop elem)]
(+ top client-top offset-top (element-top (.-offsetParent elem) top)))
top))
(defn scroll-to-id
[elem-id]
(let [elem (.getElementById js/document elem-id)
hop-count (/ speed moving-frequency)
doc-top (cur-doc-top)
gap (/ (- (element-top elem 0) doc-top) hop-count)]
(doseq [i (range 1 (inc hop-count))]
(let [hop-top-pos (* gap i)
move-to (+ hop-top-pos doc-top)
timeout (* moving-frequency i)]
(.setTimeout js/window (fn []
(.scrollTo js/window 0 move-to))
timeout)))))
@jasich
Copy link
Author

jasich commented Dec 11, 2016

ClojureScript implementation of Gabriel Delépine's Smooth-Scroll project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment