How to reset scroll on route changes in ember 3?

546 Views Asked by At

I'm trying to use hook activate, didTransition, or willTransition, but none of these work, they do nothing at all. I try to start by one route:

// app/routes/section.js
import Route from '@ember/routing/route';

export default class SectionRoute extends Route { 
  ...

  activate() { scroll(0, 0); }
}
<!-- app/templates/section.hbs -->
<h1>{{model.title}}</h1>
<p>{{model.body}}</p>
{{outlet}}
{{#each model.subsections as |s| }}
  <Section @section={{s}} />
{{/each}}

This works in my js browser console:

scroll(0, 0);

This is my router

// app/router.js
...
Router.map(function() {
  this.route('docs');
  this.route('section', { path: '/docs/section/:slug' });
});

If I make section a child of docs, it works, as long as I don't hide parent's content, but I want to hide it. An anchor in link-to component could help.

When I remove this piece of css, it works.

html {
  scroll-behavior: smooth;
}
1

There are 1 best solutions below

7
jelhan On

Your approach is working as expected. I have created an Ember Twiddle to verify that one, which you can find here. It has two routes. One which scrolls to the top when activated and one which scrolls to bottom when activated. It's scrolling as expected.

I guess you may be facing issues with the hook if transitioning between subroutes? A route is considered to stay active and the activate hook is not called

  • if a transition does not change the route but only the dynamic segments or query parameters used for the route or
  • if a transition happens between subroutes of that route.

If you want to have scroll to top on every transition or want to have more granular control, which transitions should trigger that scrolling I would recommend to use routeDidChange event of RouterService instead.