Search code examples
htmlclient-sidesingle-page-applicationcrossroadsjs

How can I implement links within a page, while using Client-side routing?


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?


Solution

  • 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); 
      });
    });