Kukula Mula
Kukula Mula

Reputation: 1869

HTML <a> jump to a specific part of a page works from the second click

I have the following HTML code in my landing page

<div class="col-12 text-center mt-4 mb-4">
   <a class="btn know-more-btn text" href="#billing">Tell Me More</a>
</div>

<div id="billing" class="billing-section">
   //show some billing options
</div>

when clicking on btn know-more-btn for the first time the screen flickers and nothing happens only from the second click it "jumps" to the right location on the page (the billing section) Not sure why this happens

Also is there a way to turn the "jump" into simulation of fast scroll to that section

Upvotes: 2

Views: 889

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24404

this will not work will with the router <a href="#billing">Tell Me More</a> ,it will trigger the router to redirect to some page or reload the page.

so one way to solve it by useing template variable and call scrollIntoView method to apply scrolling.

<div class="basic c-pointer col-12 text-center mt-4 mb-4">
   <a class="btn know-more-btn text" 
    (click)="billingElm.scrollIntoView({behavior: 'smooth'})" >
      Tell Me More 👇
    </a>
</div>

<div #billingElm class="billing-section">
   //show some billing options
</div>

stackblitz demo 🚀🚀

for reusability this the directive way

@Directive({
  selector: '[scrollTo]'
})
export class ScrollToDirective {

  @Input('scrollTo') elm:HTMLElement;

  @HostListener('click') onClick(){
    if(this.elm){
      this.elm.scrollIntoView({behavior:'smooth'});
    }
  }
}

template

<div class="col-12 text-center mt-4 mb-4">
   <a class="btn know-more-btn text" [scrollTo]="billingElm" >Tell Me More 👇</a>
</div>

<div #billingElm class="billing-section">
   //show some billing options
</div>

stackblitz demo 🌟🌟

check this Passive Link in Angular 2 - equivalent to get more details about how this problem.

Upvotes: 1

Janitha Rasanga
Janitha Rasanga

Reputation: 1126

Try this

html

<div class="col-12 text-center mt-4 mb-4" (click)="toSec()">
   <a class="btn know-more-btn text">Tell Me More</a>
</div>

ts

toSec() {
  document.getElementById("billing").scrollIntoView();
}

for smooth scrolling adding this to main style file

css

html {
  scroll-behavior: smooth;
}

Upvotes: 1

Related Questions