How to Smoothly Scroll to an Element on the Page using JavaScript
Table of Contents
JavaScript gives developers a large amount of control over the user experience of users.
One of the most useful things you can do is smoothly scroll to another element on the page.
For example, this can be used to scroll to a form element that needs filling or to a section of a page that has more information.
In this post, we will look at how to smoothly scroll to an element on the page.
How to smoothly scroll to an element
Let's start with our HTML:
HTML<main>
<button class="button">Click here to smoothly scroll</button>
<div class="content">
<p>This is sample content</p>
</div>
</main>
We have a button that will be used to scroll to the content div once clicked.
Now, let's add some CSS:
CSShtml {
scroll-behavior: smooth;
}
The magic here is the scroll-behavior
property. This property allows us to set the scroll behavior of the page, and we are setting it to smooth
.
Now all we need is some JavaScript to scroll to the element when the button is clicked:
JAVASCRIPTconst button = document.querySelector(".button");
const content = document.querySelector(".content");
button.addEventListener("click", () => {
content.scrollIntoView();
});
Now, assuming your content is tall-enough, you should be able to see the content div smoothly scroll into view when you click the button.
Conclusion
In this post, we learned how to easily smoothly scroll to an element on the page.
Simply override the scroll behavior of the page and then scroll to the element you want to scroll to.
Thanks for reading!
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js