Scroll to a specific height on button click
Sometimes you may want to scroll to a specific height on a web page when a user clicks a button. This can be useful for things like navigating to different sections of a page or revealing hidden content.
1. Scroll to a specific height on button click with JavaScript
Introduction:
Sometimes you may want to scroll to a specific height on a web page when a user clicks a button. This can be useful for things like navigating to different sections of a page or revealing hidden content.
In this blog post, we will show you how to scroll to a specific height on button click with JavaScript.
Example:
const scrollToHeight = (height) => {
window.scrollTo({ top: height, behavior: "smooth" });
};
const button = document.querySelector(".my-button");
button.addEventListener("click", () => {
scrollToHeight(500); // Scroll to 500 pixels from the top of the page
});
Output:
When the user clicks the button, the page will scroll to 500 pixels from the top of the page.
2. Scroll to a specific height on button click with React Js or Next Js
copy and paste the function and call it on button click
const scrolll = () => {
("use client"); //only for next.js developer
let pageHeight = window.innerHeight;
window.scrollTo({ top: pageHeight, behavior: "smooth" });
};
# Details
Published on January 31, 2024 • 1 min read