With jQuery you can create excellent ways to increase the interaction with the users. One such way is by creating a jQuery Scroll to Element feature. With this, you can create internal links on your web page, and when a person clicks on any such link then he is scrolled to the specific element.
This is very handy specially when the web page is quite large and with these internal links users are taken directly to the specific topics on the page.
I have created this feature in my SEO Terms tutorial. You can check it by clicking on any of the below 3 links. Once you click on them you will scrolled to the respective topic once the page is loaded.
I have specified the internal links by starting them with # character. This # is put on the href attribute of the anchor tag.
This is how it looks:
<a href="#targetDiv">Scroll to Target</a>
<div id="targetDiv"></div>
In the above jQuery Scroll to Element code it is quite clear that on clicking the Scroll to Target link the user will be scrolled to the div called targetDiv.
Now create the jQuery Scroll features for the click event on the anchor tags. The click event is applied to only those anchor tags whose href attribute starts with #. The below jQuery code does this work:
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
var targetEle = this.hash;
var $targetEle = $(targetEle);
$('html, body').stop().animate({
'scrollTop': $targetEle.offset().top
}, 800, 'swing', function () {
window.location.hash = targetEle;
});
});
That’s all for the coding part and you will see the jQuery will perform the Smooth Scroll to the target element whenever an internal link is clicked.
Download link is given below:
In the above jQuery Scroll to Element Code you will see that I have given 800 to the jQuery Animate function ($(‘html, body’).stop().animate()). This 800 is the time in milliseconds for the scroll to complete.
If you change it to a smaller value like 100 then the jQuery Smooth Scroll will change to a Fast Scroll.
$('html, body').stop().animate({
'scrollTop': $targetEle.offset().top
}, 100, 'swing', function () {
window.location.hash = targetEle;
});
You will see on clicking the internal link, it gets added in the URL of the web page. If you don’t want this then remove the last parameter (function ()) from the animate function. The updated code will look like:
$('html, body').stop().animate({
'scrollTop': $targetEle.offset().top
}, 100, 'swing');
When the web page has huge amount of content then you should provide a button (or image or link) at the bottom so that users can go to the top of the page by clicking it. This jQuery scrollTop feature can be created by just a single line of code.
The jQuery Scroll To Top code is given below:
<a id="top">Scroll To Top</a>
Clicking the above anchor will scroll user to the top.
$('#top').click(function () {
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
});