Here we’ll explain how to use jQuery to create smooth scrolling when navigating to a specific element on the page. jQuery makes scrolling effects much easier and on top of that, you make sure it works in all browsers no matter how old they are. So, if you are already using jQuery, why not take advantage of it?
Smooth scrolling to anchor on click
We will make use of the animate
function of jQuery to trigger the scroll when clicking on a specific element: [CodePen here].
All we need to doo is pass the elements we want the function to scroll and the scroll distance to the destination element:
$(document).on("ready", function() {
function scrollToAnchor(aid){
const destination = $("a[name='"+ aid +"']");
$('html,body').animate({
scrollTop: destination.offset().top
},'slow');
}
$(document).on('click', '.smooth-link', function(){
scrollToAnchor('demo');
});
});
Code language: JavaScript (javascript)
Note that the destination element will have to contain a name
property. For example:
<a name="demo"></a>
Code language: HTML, XML (xml)
You can also use the id
if you prefer, but you’ll also need to replace $("a[name='"+ aid +"']");
for $('#' + aid);
).
Let’s go with the explanation:
Let’s say you want to be able to click on a button or a link or any element on your page and smoothly scroll to it. First, we’ll need to attach the click event to it:
$(document).on('click', '.smooth-link', function(){
// Do something on click
});
Code language: JavaScript (javascript)
Now, let’s create a function that allows us to scroll to an element with a specific selector:
function scrollToAnchor(selector){
const destination = $("a[name='"+ selector +"']");
$('html,body').animate({
scrollTop: destination.offset().top
},'slow');
}
Code language: JavaScript (javascript)
The magic here, as you guessed, is the use of the animate
function of jQuery as well as the property scrollTop
. This is the beauty of jQuery making our life easier.
scrollTop
expects to receive the number of pixels that we want the page to scroll. So all we have to do is get the destination element on our destination
constant and then just get its position on the page by using .offset().top
. (See more about the offset function of jQuery.)
And putting it all together we have the resulting code you can see above.
Smooth scrolling on page load
Sometimes you might want to link a page with an anchor on the URL, for example, let’s say I want to direct my visitors to the comments section of another article, then I can use something like example.com/#comments
and expect them to land directly on the comments section of the page.
Now, you might want visitors to get a context of where they are on the page they just landed, and here’s where smooth scrolling comes in handy. It allows visitors to see where exactly they are on the page as they’ll see the page scrolling down before they land on the specific section of the page.
Here’s the code you’ll need to land on a page and scroll smoothly to the anchor on page load: [CodePen here]
$(window).on("load", function() {
var anchor = window.location.hash.replace('#', '');
scrollToAnchor(anchor);
});
function scrollToAnchor(selector){
const destination = $("a[name='"+ selector +"']");
$('html,body').animate({
scrollTop: destination.offset().top
},'slow');
}
Code language: JavaScript (javascript)
The code looks quite similar to the previous scenario but in this case, we are waiting for all elements on the page to load before calling our scrollToAnchor
function. This is especially important if you have images that take some time to load, as normally the height of those images is not determined until they completely load. So, images that are yet to load can appear with a height of 0 and only get their final height once the image completely loads.
So, to fix that, we add this:
$(window).on("load", function() {
// All images are now loaded
});
Code language: JavaScript (javascript)
Then we get the URL anchor with window.location.hash
and use it instead in our call to the scrollToAnchor
function. That should return #comments
for our example. But we just need the word comments
which is the value our destination element will have. (<a name="comments"></a>
). So let’s just remove the #
part too using replace
:
scrollToAnchor(window.location.hash.replace('#', ''));
Code language: JavaScript (javascript)
Now we add the same scrollToAnchor
we applied on our previous example and that’s it!
Smooth scrolling inside a scrollable element
Let’s say you want to be able to scroll inside an element that has a scrollbar and uses overflow: scroll
. How can we do this?
Easy, we just change the element we want to apply the animation to:
// Our element now has id #destination
$('#destination').animate({
scrollTop: destination.offset().top
}, 8000);
Code language: JavaScript (javascript)
Here’s an example:
Changing the animation effect (easing)
jQuery comes with 2 different animation effects we can choose from. Those are called “easing functions” and we can apply one or another depending on our preferences.
By default jQuery uses swing
, but we can also use linear
.
Here’s an example:
$('#destination').animate({
scrollTop: destination.offset().top
}, 8000, "linear");
Code language: JavaScript (javascript)
We can add even more effects if we include this file. You can see their names on the code (easeInQuad, easeOutQuad, easeInOutQuad etc.)
Configuring the scrolling speed
The animate
function of jQuery allows us to configure the speed. In this example, we are using a predefined value by using slow
.
The possible predefined values are:
slow
= 600 millisecondsnormal
= 400 millisecondsfast
= 200 milliseconds
You can, if you prefer, define your own duration in milliseconds, just pass it instead of any of these values. Here’s an example:
// 8 seconds animation
$('html,body').animate({
scrollTop: destination.offset().top
}, 8000);
Code language: JavaScript (javascript)
Doing something when the animation ends (callbacks)
The animate
function of jQuery provides what we call “callbacks”. Functions that get executed once certain even takes place. In this case, the animate function executes a function once the animation has finished.
Here’s what it looks like:
// 8 seconds animation
$('html,body').animate({
scrollTop: destination.offset().top
}, 8000, function(){
// This is the callback function
// Whatever you run here will get executed
// once the animation finishes
alert("Done scrolling");
});
Code language: JavaScript (javascript)
Conclusion
In this article we’ve covered the most common scenarios for a smooth jQuery scroll to elements’ anchors within the same page. This is all you need to know about this particular feature. But if you miss anything please let us know in the comments.
If you are looking for more scroll animations, check out the best jQuery Carousel plugins.