Reputation: 3163
I'm working on an SPA, using crossroads.js for the client-side routing. Everything is working perfectly, with one exception.
I have one page within this SPA that is quite large, and I'd like to be able to use internal links, to provide a table of contents at the top. In the past, I've done something like this:
<ul>
<li><a href="#Introduction">Introduction</a></li>
<li><a href="#Chap1">Chapter 1</a></li>
<li><a href="#Chap2">Chapter 2</a></li>
<li><a href="#Chap3">Chapter 3</a></li>
</ul>
These would link to elements within the same page with the corresponding ID.
However, now that I'm using client-side routing, this doesn't seem work work as well. The page that this I'm using this on has a URL like:
http://myserver.com/#/Books/12/Full
Clicking one of the links above does move the page to the correct location on screen, but it changes the URL to:
http://myserver.com/#Chap2
Is there a standard way of handling internal links in an SPA, while preserving the URL?
Upvotes: 2
Views: 177
Reputation: 3163
@mdesdev got me pointed in the right direction, but here's what ultimately wound up working for me:
Using an SPA, the page in question is loaded after the document is loading, so I couldn't get using the jQuery document ready function to add the click handler to work. Instead, I created the following function:
function scrollToInternal(target) {
// #MyContent is the div that needs to be scrolled
$('#MyContent').scrollTop($(target).position().top);
};
Then in my markup, I called this function with the onclick attribute:
<ul>
<li><a href="#" onclick="scrollToInternal('#Introduction');return false">Introduction</a></li>
<li><a href="#" onclick="scrollToInternal('#Chap1');return false">Chapter 1</a></li>
<li><a href="#" onclick="scrollToInternal('#Chap2');return false">Chapter 2</a></li>
<li><a href="#" onclick="scrollToInternal('#Chap3');return false">Chapter 3</a></li>
</ul>
Not as elegant a solution as mdesdev's, but it's working.
Upvotes: 0
Reputation: 5610
Here's a FIDDLE
<nav>
<ul>
<li data-rel="div1">DIV 1</li>
<li data-rel="div2">DIV 2</li>
<li data-rel="div3">DIV 3</li>
</ul>
</nav>
<div id="div1">
</div>
<div id="div2">
</div>
<div id="div3">
</div>
$(function() {
$('nav ul li').click(function() {
$('html, body').animate({ scrollTop: $('#'+$(this).data('rel')).offset().top }, 900);
});
});
Upvotes: 1