2

I'm serving a simple page using BackboneJS with its router.

On one of my DOM elements, I have

<div id="1234">Content</div>

and when I go to

http://www.myhomepage.com/page#1234

I want the page to scroll to where that DIV is located (which is the expected behaviour).

But since I'm using Backbone, it must be interfering with it because it isn't working properly. I read the backbone document and it seems like it's not recognizing the hash value, and I suppose I can set up "Catch all" route for all un-matched ones (Is there a way to catch all non-matched routes with Backbone?)

But how do I actually make this behave the way I would like (i.e. make the page scroll to the right div)?

Community
  • 1
  • 1
ericbae
  • 9,604
  • 25
  • 75
  • 108

1 Answers1

0

Ok, first a little background. In the early days of the web, browsers had these things called anchors, or as you now know them, a tags:

<a name="foo">

Anchors let you "bookmark" a part of a page, so that you could then link to that part specifically:

<a href="#foo">

Eventually, browsers added ID attributes as anchors also.

Then modern JS and Backbone came along, and that's where the trouble started, because the Backbone router hijacks that system. This means that if you want to use Backbone's router, you lose the ability to have normal anchors.

However, all is not lost. One option is to make Backbone not use the URL hash for it's router, and instead rely on the browser's "push state". You can do this by passing an extra option when you start the router:

 Backbone.history.start({pushState: true})

You can read more about the limitations of that approach here: http://backbonejs.org/#History

but the short version is that it will only work for the browsers marked in green here:

http://caniuse.com/#search=pushstate

Another approach would be to re-create your own anchor system, using jQuery. Basically you can create a fallthrough for when none of your routes match:

 if (!Backbone.history.start() {

and then in that fallthrough you can use jQuery to manually scroll to the desired point:

     $('html, body').animate({
         scrollTop: $('#' + window.location.hash).offset().top
     }, 1000);

You could also get fancy and define custom routes instead of using a fallthrough, but I'll leave that up to you.

In addition to these options @Pramod linked to a question with answers containing still other options you could also consider (like modifying the Backbone router to build scrolling functionality in).

machineghost
  • 33,529
  • 30
  • 159
  • 234
  • Anybody know how to accomplish the manual scroll with ReactJS. – Chris Dolphin Mar 12 '15 at 07:27
  • Asking a separate question in the comments is the wrong way to get help here on Stack Overflow. You will have more success if you actually start a new (Stack Overflow) question for your question instead. – machineghost Mar 12 '15 at 18:15