How do I keep on the same page by clicking on internal anchor links, using Aurelia?
Asked Answered
M

2

6

I am working on a styleguide for a project and currently I would like to have a basic clicking behaviour on anchor links, so that they scroll to the correspondent id.

As an example:

<a href="#section"></a>

That scrolls down to:

<div id="section"></div>

In Aurelia, the default behaviour is to treat links as routes. I can't get the internal link to work, as it immediately sends me to an external page.

Does someone know how to overcome this issue? Thanks!

Mnemonic answered 8/2, 2019 at 13:39 Comment(0)
A
5

You can disable the Aurelia router highjacking the link in several different ways, as per the documentation. One of the ways is to use one of these special attributes:

<a href="/some/link" download>Skip Hijacking</a>
<a href="/some/link" download="">Skip Hijacking</a>
<a href="/some/link" router-ignore>Skip Hijacking</a>
<a href="/some/link" router-ignore="">Skip Hijacking</a>
<a href="/some/link" data-router-ignore>Skip Hijacking</a>
<a href="/some/link" data-router-ignore="">Skip Hijacking</a>
Anticipant answered 8/2, 2019 at 13:55 Comment(1)
Thank you so much. Router ignore works like a charm ;)Mnemonic
D
0

Just add an click event handler to your link and use scrollIntoView().

Here is a working fiddle, open it in a full screen page to test it :)

document.getElementById('myLink').onclick = function(e){
  document.getElementById('myDiv').scrollIntoView();
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
</head>
<body>
<a id="myLink">Click me!</a>
    <br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>  
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>  
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>  
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
    .<br/>
  <div id="myDiv">Hi there!</div>
</body>
</html>
Dodiedodo answered 8/2, 2019 at 13:46 Comment(2)
Thanks for your answer, though it's not the approach I'd like to adopt :) but it is also effective.Mnemonic
No problem, my pleasure anyway :)Dodiedodo

© 2022 - 2024 — McMap. All rights reserved.