6

I have a #content div and a button component.

When I click the button, I want to scroll to the top of the #content div.


HTML:

<div id="content">
    Loren ipsum 
</div>
<div (click)="toTop($event)">top</div>

topscroll.component.ts:

export class TopscrollComponent implements OnInit { 
  constructor() { } 

  ngOnInit() { }

  toTop(event){ 
    ...
  }
}

2 Answers 2

21

You can do that with plain javascript using .scrollIntoView():

toTop() {
  document.getElementById("content").scrollIntoView();
}

Note: you don't need event.

Sign up to request clarification or add additional context in comments.

9 Comments

I want to set specific id="content"...bcoz i have written scroll css only for that id
Aah, you want to scroll to the top of the #content div?
Yes..i am expecting that one
What does console.log(top) say? Is it undefined, or a number?
getting number only
|
0

Get the div class or id using query selector and scroll into it

 const divElement: HTMLElement = document.querySelector('.div-class-name') as HTMLElement;
 if(divElement){
  divElement.scrollIntoView({ behavior: 'smooth' });
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.