Skip to content

Instantly share code, notes, and snippets.

@paultopia
Last active June 7, 2018 22:29
Show Gist options
  • Save paultopia/e67da7899cdf52a677169de0edcd5d87 to your computer and use it in GitHub Desktop.
Save paultopia/e67da7899cdf52a677169de0edcd5d87 to your computer and use it in GitHub Desktop.
Floating navbar with only a single css property changed (thanks to the magic of reagent, a clojurescript interface to react)
;; I think this will work. It's extracted from a working version here:
;; https://github.com/paultopia/stdio (mostly in the nav namespace)
;; so if you try this and it doesn't work, I probably left something off, feel free to go to the original.
(ns navbar.core
(:require [reagent.core :as r :refer [render atom]]))
(defn loren [reps]
(apply str (take reps (repeat "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum."))))
(def scrollpos (atom 0))
(defn update-scroll []
(reset! scrollpos (.-pageYOffset js/window)))
(defn track-scroll []
(.addEventListener js/window "scroll" update-scroll))
(defn crazyfloat [sp]
(cond
(< sp 30) "static"
:else "fixed"))
(defn navbar []
[:div {:style {:position (crazyfloat @scrollpos)}}
; components containing navbar items go here
])
(defn das-page []
[:div
[navbar]
[:p (loren 10]])
(track-scroll)
(render [das-page] (.getElementById js/document "app"))
@paultopia
Copy link
Author

paultopia commented Jul 2, 2016

This is an insane hack to avoid writing CSS. Uses reagent to implement a floating top navbar from scratch without changing more than a single CSS property. The strategy is just to hook an event listener on scroll that updates a ratom containing the y-axis position, and then make the position property of the div containing the navbar depend on that.

Which is nutty, and makes the navbar appear to jump around a teensy bit, but is so so so so much nicer than having to fight with css to get the elements under the navbar positioned correctly with respect to it.

@andrewzhurov
Copy link

Looks simple, already playing with it :)

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