LambdaTest Community

Find answers, support, and inspiration from other users

LambdaTest Community

How can I create a smooth scroll with jQuery?

Please someone give me a tutorial on how can I create a smooth scroll with jQuery.

Up Vote Down Vote 1 Votes
Posted 3 months ago


Jquery is yet another method that gives us the liberty to implement smooth scrolling with even more control than JavaScript. Implementing a smooth scroll with Jquery allows us to control the time it should take to scroll to the target element. In other words, you can manage the speed of scrolling.

Before referring to the following code for a smooth scroll in Jquery, make sure you have no other code that influences the scrolling behavior of the web page.

 $(".navbar a").on('click', function(event) {
 if (this.hash !== "") {
 var hash = this.hash;
 $('html, body').animate({
 scrollTop: $(hash).offset().top
 }, 1300, function(){
 window.location.hash = hash;

Taking this snippet and connecting back to the steps I mentioned above, we get the following:

Detect The Element

$(".navbar a").on('click', function(event)

In this code, I am selecting all the anchor tags located within the class named navbar. For all such elements, a function will be triggered when they are clicked.

Define How Much To Scroll

scrollTop: $(hash).offset().top
 }, 1300

The above code for a smooth scroll in Jquery calculates the offset of the attribute with “hash” and returns the pixel value back.

The value 1300 refers to the time in milliseconds that I want the web page to take before reaching the target location i.e. window.location.hash.

This code for smooth scroll in Jquery generates the following output:

Up Vote Down Vote 0 Votes
Posted 3 months ago
1 Answer
3 months ago