-
-
Save andreortiz82/7e01a69bc8f3d5ed28d78fbb334227b8 to your computer and use it in GitHub Desktop.
(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") |
Also line 10:
When comparing against nil
(assuming that's what you want, more on this in a second) you don't need an explicit comparison like
(if (= data nil)
:foo
:bar)
which is the same as
(if-not data
:foo
:bar)
nil
and false
are the only values that don't pass an (if)
test. Everything else will—including empty strings. The best way to check for those is:
(ns foo
(:require [clojure.string :as str]))
(if-not (str/blank? input)
(foo input)
(bar input))
Let's talk about line 25's call to (html)
later. Is it needed?
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)]
...)
Let's have a chat about some of this over running code. There's lots more fun stuff to explore!
Some ClojureScript syntactic sugar can make line 16 nicer:
(set! (.-innerHTML (js/document.getElementById "tooltip-container") "")
No need to call
(str)
on a string literal""
. Now I'll look at the main question you raised...