Skip to content

Instantly share code, notes, and snippets.

@andreortiz82
Created February 26, 2019 02:17
Show Gist options
  • Save andreortiz82/7e01a69bc8f3d5ed28d78fbb334227b8 to your computer and use it in GitHub Desktop.
Save andreortiz82/7e01a69bc8f3d5ed28d78fbb334227b8 to your computer and use it in GitHub Desktop.
Quick tooltip spike
(defn tooltip-handler
"This method listens for mouse over/out events and injects the DOM with an HTML element"
[{:keys [data]} event]
(let [position (-> event .-target .getBoundingClientRect)
width (.-width position)
height (.-height position)
x (+ (.-left position) 20)
y (.-top position)
output data]
(if-not (= data nil)
(-> js/document
(.getElementById "tooltip-container")
(.-innerHTML)
(set!
(str "<div class=\"global-tooltip\" style=\"top: " y "px; left: " x "px;\">" output "</div>")))
(-> js/document
(.getElementById "tooltip-container")
(.-innerHTML)
(set!
(str ""))))))
(defn some-component
"This is a useless component for this example. On-mouse-over `tooltip-handler` is called and passed some data."
[]
[:div {:on-mouse-over #(tooltip-handler {:data (html [:div "demo"])} %)}])
(defn tooltip-container []
[:div {:id "tooltip-container")
@christianromney
Copy link

I know this is just a sample, too, but still it's best to use every possible line to learn from. Rather than embedding the container id in the handler function, it should be passed in as an argument for flexibility. And there's one more cool interop macro that in this case will only save you 2 characters, but at other times is even more useful:

Before:

(let [position (-> event .-target .getBoundingClientRect)] 
  ...)

After:

(let [position (.. event -target getBoundingClientRect)] 
  ...)

@christianromney
Copy link

Let's have a chat about some of this over running code. There's lots more fun stuff to explore!

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