Linking to Content on the same page & <LinkTo> component

When I want to link to some content, on the same page, with standard html I would do something like:

<a href="#jsmith">Click here to learn about John Smith.</a>
 <!--  somewhere further down the page  -->
<a name="jsmith">John smith says hello</a>

I tried to replicate the code above with <LinkTo>, because I thought it was the ‘emberic’ way to do things. Besides the docs mention the whole convention over configuration idiom.

Anyway I got an error saying;

“you didn’t supply a model … #jsmith route does not exist etc”

and rightfully so in my opinion. I never added a #jsmith route to router.js.

So the example code I wrote above is not a use case of the <LinkTo> component?

The answer to this question answers on my question somewhat indirectly, so I apologize if my question is repetitive.

1 Like

Part of the problem is that Ember supports two types of routing URLs: history and hash that use different browser APIs. The hash version uses url hashes which are also used for anchors. So because linkto and the ember router support that hash url type it thinks you’re trying to link to a route rather than an anchor.

So try using regular <a> tags if that works (i haven’t tried it personally), the other alternative would be using the query param method used by addons like ember-anchor. Not sure how well maintained that addon is so if you go that route consider rolling your own similar solution if you’re concerned about it.

Incase someone stumbles on this issue for what I was searching for (simply scrolling to the anchor after a transition).

My solution:

app/initializers/router-scroll.js - scrollToTarget being a custom helper that simply scrolls to the selector/element.

import Route from '@ember/routing/route';
import { next } from '@ember/runloop';
import { scrollToTarget } from 'postedin/helpers/scroll-to-target';

export function initialize() {
  Route.reopen({
    activate() {
      this._super();

      next(() => {
        if (! scrollToTarget(window.location.hash)) {
          window.scrollTo(0, 0);
        }
      });
    },
  });
}

export default {
  initialize,
};