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?
A named anchor is a label assigned to part of an html message to which you can jump to by clicking a link that is in another part of the message, e.g. if you create an anchor named 'top' at the top of the message, inserting a link to that anchor far below the top will allow the reader to click the link and make the ...
An anchor name is the value of either the name or id attribute when used in the context of anchors. Anchor names must observe the following rules: Uniqueness: Anchor names must be unique within a document. Anchor names that differ only in case may not appear in the same document.
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:
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With