niloofar
niloofar

Reputation: 2334

Clojure sending data with nested vector to function and use the items

First, I'm sorry if my question is something simple or not clear. I'm almost new to Clojure and I need help.

I want to create a function to generate some HTML link for a menu. This is what I have now and it works fin:

(defn test-function [title-id title-name]
    [:span {:onclick #(.scrollIntoView (.getElementById js/document title-id))
            :style {:color :red} title-name])


[:li (test-function "title-1-id" "title-1-name")]
[:li (test-function "title-2-id" "title-2-name")]

But as I have many li tags, I want to have something like this to send to the function, and the function can generate the links for me, exactly like what the current code do for me. But I didn't find how to do that yet, and have no idea if I should use vector or something else.

[["title-1-id" "title-1-name"] ["title-2-id" "title-2-name"]]

Thank you in advance.

Upvotes: 1

Views: 67

Answers (1)

Martin Půda
Martin Půda

Reputation: 7576

You can use for, then destructure each element into id and name (I just renamed name to li-name to avoid shadowing function name) and wrap whole for in [:ul ... ]:

[:ul
             (for [[li-id li-name] [["id1" "Scroll to red"] ["id2" "Scroll to pink"]]]
                  [:li {:style {:cursor :pointer
                                :color :red}
                        :on-click #(.scrollIntoView (.getElementById js/document li-id))}
                   li-name])]

[:div
             [:div [:img#id1 {:src "" :style {:width 600 :height 1000 :background "red"}}]]
             [:div [:img#id2 {:src "" :style {:width 600 :height 1000 :background "pink"}}]]
             [:div [:img#id3 {:src "" :style {:width 600 :height 1000 :background "yellow"}}]]]

Note that you even don't need Javascript to scroll to target element- [:a ... ] can point to the object on the same page:

[:ul
             (for [[li-id li-name] [["id1" "Scroll to red"] ["id2" "Scroll to pink"]]]
                  [:a {:href  (str "#" li-id)
                       :style {:color           :red
                               :cursor          :pointer
                               :text-decoration :none}}
                   [:li li-name]])]
            [:div
             [:div [:img#id1 {:src "" :style {:width 600 :height 1000 :background "red"}}]]
             [:div [:img#id2 {:src "" :style {:width 600 :height 1000 :background "pink"}}]]
             [:div [:img#id3 {:src "" :style {:width 600 :height 1000 :background "yellow"}}]]]

Upvotes: 2

Related Questions