-
-
Save ajchemist/653e6284bf6ac7e885ea872d7ff71ef5 to your computer and use it in GitHub Desktop.
ClojureScript scroll element into view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment