6

In a SPA, using a navigation framework such as Sammy.js, how could I use in page named anchors for in-page navigation?

e.g. Say I have a route like localhost/myapp/#/somerecord/1 where the application loads somerecord with id = 1.

However somerecord is really complicated and long. I want to be able to jump to a certain section using a named anchor.

Say an article element is defined like <article id=section-d> ... </article> and I just link to like <a href=#section-d>Section D</a> it technically works, but the URL reads like localhost/myapp/#section-d, this breaks the navigation stack. Hitting the Back button takes me back to localhost/myapp/#/somerecord/1 and without jumping back to the top.

The preferred action would be to either jump back to the top or to the previous page. Any ideas on how to accomplish this?

danwellman
  • 9,068
  • 8
  • 60
  • 88
Doguhan Uluca
  • 6,933
  • 4
  • 38
  • 51
  • This is a duplicate of http://stackoverflow.com/q/10113103/829970, but that one only has bad answers (i.e. answers for plain Javascript without sammy.js). – Moshe Katz Mar 12 '13 at 05:22
  • Also a duplicate of http://stackoverflow.com/questions/9351231/scroll-to-anchor-link-in-a-sammy-js-project – Moshe Katz Mar 12 '13 at 05:23

2 Answers2

3

Effectively, you have to define your URL as a regular expression, and allow an optional bookmark hash at the end of it; something like:

get(/#\/somerecord\/(\d+)(#.+)?/, function() {
    var args = this.params['splat'];
    var recordId = args[0];
    var articleId = args[1];
});

This should match any of the following routes:

  • #/somerecord/1
  • #/somerecord/1# (treated as if there is no article id)
  • #/somerecord/1#section-d (articleId = '#section-d')

You should then be able to use the articleId to find the matching element and manually scroll. e.g. in the last route above, using jQuery you could do something like:

var $article = $(articleId);
    $(document.body).animate({ scrollTop: $article.offset().top });
});

I've just written up a more comprehensive article about this (using Durandal), if you're interested: http://quickduck.com/blog/2013/04/23/anchor-navigation-durandal/

Edit Link is dead. The article available here http://decompile.it/blog/2013/04/23/anchor-navigation-durandal/

JamesT
  • 2,988
  • 23
  • 29
gerrod
  • 6,119
  • 6
  • 33
  • 45
1

I've had the same problem using durandal with sammy.js. Basically, you have to create a (invisible) route for each anchor you want on your page. See a post from me about the solution I found: http://papamufflon.blogspot.de/2013/04/durandal-scrollspy.html

Papa Mufflon
  • 17,558
  • 5
  • 27
  • 35