How can I let the page scroll to a specific word in a longer text

Viewed 134

I have a long text and want (if I choose a word before) the page to scroll to this element automatically, after pressing a button. The text where the word is in, is much longer than this, I just wanted to demonstrate my problem.

<div (click)="scrollto()">scroll to word</div>
<div id="text">lsja dflkasjdf laksj dflkasj scrollhere saldfj asljfals dfalsjölas dfasjd fajsdlfa jsdldsa fasl falsd flasf</div>

.ts file:

scrollto() {
  const word = 'scrollhere';

what do I have to write in the Typescript code to let the page scroll to the word 'scrollhere'?

1 Answers

A way of doing it is wrapping the word you want to scroll to in a span or other semantic element so you can reference it in your .ts file. Something like this:

<span #scrollHere>scrollhere</span>

And then in your .ts

@ViewChild('scrollHere', { static: true }) scrollHere;


scrollTo() {
  this.scrollHere.nativeElement.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
}
Related