Anchor link to direct to a div does not work

Asked

Viewed 767 times

1

I’m using Angular 2+, I’m trying to add an anchor that when clicked will take me to the target div, but when I click the anchor, my site is reloaded and adds the #parallaxdiv link after the localhost... instead of moving to the link.

I tried something like:

<a href="#parallaxdiv">Teste</a>

<div id="parallaxdiv"></div>

2 answers

2


I managed to solve using:

TS

scroll(el: HTMLElement) {
    el.scrollIntoView();
}

TEMPLATE

<a (click)="scroll(target)"

<div #target>Your target</div>
  • Our top too, a long time ago looking for this rsrs

0

It is worth noting that for this to work using the marked solution, it is necessary to have a method named scroll and that receives a parameter. In the scroll(param) case it would be an example of signature.

You can use ready-made solutions as well as Smoothscroll, that even allows you to configure some other features, such as smooth scrolling and scrolling time setting. It has simple and complete documentation, but anyway follows example below:

<!-- Script CDN para ancora -->
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@15/dist/smooth-scroll.polyfills.min.js"></script>

<script>
  let scroll = new SmoothScroll('a[href*="#"]', {
    speed: 300,
  speedAsDuration: true,
  <!-- History -->
    updateURL: true, <!-- Update the URL on scroll -->
    popstate: true <!-- Animate scrolling with the forward/backward browser buttons (requires updateURL to be true) -->

});

Done this is only use normally in HTML as you did in the problem description:

<a href="#parallaxdiv">Teste</a>
<div id="parallaxdiv"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.