The JavaScript scrollTo()
method used to smoothly scroll to a particular set of coordinates inside a given element.
Syntax of Javascript scrollTo function
element.scrollTo(x-coord, y-coord)
element.scrollTo(options)
// Examples
element.scrollTo(0, 1000);
//Using ScrollToOptions
element.scrollTo({
top: 100,
left: 100,
behavior: 'smooth'
});
x-coord
is the pixel along the horizontal axis of the element that you want displayed in the upper left.y-coord
is the pixel along the vertical axis of the element that you want displayed in the upper left.- Also, we can pass an options object by specifying behavior as smooth
<!DOCTYPE html>
<html>
<head>
<title>JavaScript scrollTo function</title>
</head>
<body>
<nav>
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
</nav>
<section id="section1">
<h2>Section 1</h2>
<p>
Pellentesque a fermentum eros. Sed nec ornare ex, ac egestas neque. Pellentesque odio urna, sollicitudin sit amet elit non, aliquam consectetur lectus. Maecenas purus lacus, fermentum nec ultricies a, consequat quis eros. Ut vitae sapien sit amet augue aliquet placerat sit amet non erat. Fusce dui purus, viverra in justo feugiat, tincidunt fringilla elit. Curabitur eget eros sagittis, finibus sem in, rutrum sapien. Sed leo quam, cursus quis tellus a, aliquet pharetra ex. Nulla facilisi. Suspendisse potenti.
</p>
</section>
<section id="section2">
<h2>Section 2</h2>
<p>
Pellentesque a fermentum eros. Sed nec ornare ex, ac egestas neque. Pellentesque odio urna, sollicitudin sit amet elit non, aliquam consectetur lectus. Maecenas purus lacus, fermentum nec ultricies a, consequat quis eros. Ut vitae sapien sit amet augue aliquet placerat sit amet non erat. Fusce dui purus, viverra in justo feugiat, tincidunt fringilla elit. Curabitur eget eros sagittis, finibus sem in, rutrum sapien. Sed leo quam, cursus quis tellus a, aliquet pharetra ex. Nulla facilisi. Suspendisse potenti.
</p>
</section>
<script>
// Get the link element
const link = document.querySelector('a[href^="#"]');
// Add an event listener to detect when the link is clicked
link.addEventListener("click", (event) => {
// Prevent the default link behavior
event.preventDefault();
// Get the target element
const target = document.querySelector(
link.getAttribute("href")
);
// Get the position of the target element
const targetRect = target.getBoundingClientRect();
// Scroll to the position of the target element
window.scrollTo({
top: 100,
left: 100,
behavior: "smooth",
});
});
</script>
</body>
</html>

Our team of experienced developers is dedicated to sharing their knowledge and expertise with the community through engaging and informative articles and tutorials. We cover a wide range of topics, from the basics of JavaScript and React.js to advanced techniques for building modern web applications with Next.js.