Reputation: 115
I have been trying out some things to get more used to web dev.
I found a cool thing; scrollIntoView(), where it it is supposed to scroll smoothly to the next id-tag.
<button type="button"
onclick="document.querySelector('#projects-overview')
.scrollIntoView({behavior: 'smooth'});">
Click Me!
</button>
And this should smoothly scroll to id: projects overview in dashboard.component.html:
<div class="grid-container">
<h1 id="projects-overview" class="mat-h1">Projects</h1>
Now this works, in a sence that it "goes" to the id, but it does not do this smoothly?
Any help/comments are really appreciated.
i made this in an Angular project, and the latest edition of Chrome
SNIPPET can be found here: FIDDLE
Upvotes: 1
Views: 4862
Reputation: 115
I found out that there is a option in Chrome to disable/enable smooth scrolling options (which i had turned to default so it didn't work.)
To enable smooth scrolling in Chrome go to: chrome://flags/#smooth-scrolling
it all works smoothly now.
furthermore i found that there are multiple ways to scroll smoothly:
#1: in the CSS:
html, body {
height: 100%;
scroll-behavior: smooth;
}
#2: in the HTML itself
<button type="button"
onclick="document.querySelector('#projects-overview')
.scrollIntoView({behavior: 'smooth'});">
Click Me!
</button>
Upvotes: 0
Reputation:
I tested your code, extracting the JavaScript out of the HTML fixes the issue.
The error I get in the console when running your code is Cannot read property 'scrollIntoView' of null
const buttonEl = document.querySelector("#clickMe");
const scrollEl = document.querySelector("#scollToMe");
buttonEl.addEventListener("click", function () {
scrollEl.scrollIntoView({
behavior: "smooth"
})
})
.scroll-el {
margin-top: 200vh;
background: red;
height: 50px;
width: 100%;
}
<button id='clickMe' type='button'>Click me</button>
<div class='scroll-el' id='scollToMe'></div>
Upvotes: 1