Smooth Scroll to ID with jQuery

Smooth scroll to ID with jQuery improves the web project’s user interface. Users’ attempts to scroll to a certain area of the page are reduce when using the smooth scroll. By hitting an anchor link or button, the user may navigate to a specified section of the website using smooth scrolling.

The jQuery scrollTop function makes scrolling to a div element simple. You may also use the jQuery animate() function to add motion to the page scroll. In this tutorial, we’ll teach you how to use jQuery to create a smooth scroll to a div without having to manually scroll.

smooth Scroll to Id with Div

For single-page websites, the Scroll to Div feature is quite beneficial. It allows the user to get to a certain page segment without having to manually scroll through the pages. Using jQuery, the sample code scrolls to div and jumps to a certain section of the page by clicking on the anchor link.

Here’s a small bit of jQuery code I use frequently when I need to scroll to an ID in a seamless manner. Simply modify the 500 to the desired page scrolling speed (in milliseconds).

Example:

HTML part:

<a href="#one">One</a>
<a href="#two">Two</a>

<hr>

<div id="one">First Element</div>

<hr>

<div id="two">Second Element</a>

	<hr>

CSS part:

hr {
	height: 100vh;
}

JQuery Part:

$("a[href^='#']").click(function(e) {
	e.preventDefault();
	
	var position = $($(this).attr("href")).offset().top;

	$("body, html").animate({
		scrollTop: position
	} /* speed */ );
});

To link to a specific region of a web page, we utilize the # (hash) in the href property of the HTML anchor element. For example, <a href=”#one”> may be used to scroll to the top of the current page, and <a href=”#two”> can be used to scroll to the bottom of the page. When you click a link with the #, you will be sent to a specific point on the website.

Conclusion

Hopefully, this quick and easy script can assist you in adding smooth scrolling to your website. It allows you to add scroll to an element in less than a minute. You may simply customize the Auto-Scroll to Div feature to meet your own requirements. Add a back-to-top button to the web page to make the scroll-to-div functionality more user-friendly.

That’s all for this article if you have any queries please contact us through our website or email us at [email protected]

Leave a Comment