erikringsmuth / app-router

Router for Web Components
https://erikringsmuth.github.io/app-router/
MIT License
610 stars 83 forks source link

Scroll to hash fragments and history scroll position #46

Closed erikringsmuth closed 9 years ago

erikringsmuth commented 9 years ago

Two difficult things in client-side routing:

I want to get these features working if possible. In the mean time you can do something equivalent to hash links with a scrollTo query parameter like this.

http://example.com/page?scrollTo=elementId

<polymer-element name="demo-app">
  <template>
    <app-router id="router" on-activate-route-end="{{scrollTo}}">
      <app-route path="/" import="/pages/home-page.html"></app-route>
      <app-route path="/page" import="/pages/other-page.html"></app-route>
      <app-route path="*" import="/pages/not-found-page.html"></app-route>
    </app-router>
  </template>
  <script>
    Polymer('demo-app', {
      scrollTo: function(event) {
        // look for a scrollTo query parameter
        if (event.details.model.scrollTo) {
          var el = document.querySelector('#' + event.details.model.scrollTo);
          if (el && el.scrollIntoView) {
            el.scrollIntoView(true);
          }
        }
      }
    });
  </script>
</polymer-element>

You can find the documentation on scrollIntoView() here https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollIntoView.

This isn't supported by all browsers, but it's an example of a workaround. Tweak it to your needs and hopefully I can find a way to make the router scroll correctly when possible.

erikringsmuth commented 9 years ago

Fixed and released in v2.2.0 https://github.com/erikringsmuth/app-router/blob/master/changelog.md#v220.

There is still an issue with browser history (back or forward) scrolling to the correct position when using Polymer's core-scaffold or other layout elements. It may be because only the content section of the screen is scrolled and the history doesn't recognize that it needs to scroll that section. I think it's a Polymer bug...