Trouble with fragment identifiers in a SPA

Hey,

I am wondering how to best cope with fragment identifiers in single page applications. I am currently playing around with reitit and have modified their re-frame example a bit, as it is a very similar to my current setup, but I am unable to make the links work with the identifiers. Here is the modified version as a gist. The two main pages are as follows:

(defn home-page []
  (fn []
    [:div
     [:h1  "This is home page"]
     [:button {:on-click #(re-frame/dispatch [::navigate ::sub-page1])}
      "Go to sub-page 1"]
     [:br]
     [:a {:href "/sub-page1#foo"} "Go to sub-page 1 and fragment foo."]]))

(defn sub-page1 []
  [:div
   [:h1 {:style {:height "2000px"}} "This is sub-page 1"]
   [:p {:id "foo"}
    "Fragment identified paragraph"]])

When going to sub-page 1 via the fragment link I don’t end up at the paragraph identified by foo

So the question is how to make the above example work so I end up at the correct paragraph when the url contains a fragment identifier. I am also happy to use another approach if that is better suited in this case. I essentially just want to be able to link to certain resource in a page with a link and wonder how this is done these days. If it would work with reitit and history that would be even better.

IIRC you need an <a name=”foo”></a> somewhere on your sub page, I don’t remember this working with arbitrary elements and the id attribute. MDN lists name as „obsolete since HTML5” though, so no guarantees.

You could also read out the fragment (window.location.hash I believe) on mount and decide which element to scroll to (myElement.scrollIntoView()), or use a library to register a callback on fragment changes. Both are more work but give more control too.

Edit: Forgot I‘m posting on a Clojure board so the code would be (.. window -location -hash) and (.scrollIntoView myElement) respectively.

Hey. I am aware how it works in general and for example with static pages the fragment linking works fine, even across pages.

<!DOCTYPE html>
<html>
<body>

  <p style="height:2000px">
    My first paragraph.
    <a href="#foo"> Go to second paragraph </a>
  </p>

  <p id="foo">My second paragraph.</p>

</body>
</html>

What I am struggling is why it doesn’t work in the clojurescript SPA described above.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.