Thursday, 18 April 2013

jQuery: scroll to the top, to a specific container and to the bottom of a page


Some time ago I wrote an article where we discussed how to use JavaScript to create a smooth scroll to the top of the page.
Today we are going to see how to do it with jQuery, and we are going to do it in order to scroll to the top of the page and even to the bottom of the page. After that we are going to create a simple jQuery function that will scroll to a specific element of the page.

Interested? Ok... follow me.

Top and Bottom
The code is very simple. First of all, include the jQuery library in the head of your document (this is valid for the second example as well):
<script type="text/javascript" src="yourPath/jquery.min.js"></script>
After that, we create two links: one for the scroll-to-top, and one for the scroll-to-bottom. Remember to place them where you need them!
<a href="javascript:scrollToBottom()">Bottom</a>
<a href="javascript:scrollToTop()">Top</a>
Now, again in the head of your document the jQuery script:
<script type="text/javascript">
    function scrollToBottom() {
        $('html, body').animate({scrollTop:$(document).height()}, 'slow');
    function scrollToTop() {
        $('html, body').animate({scrollTop:0}, 'slow');
And we're done.

Scroll to a specific point
Now... if we need to scroll to a specific point on a page, we can create a target element, like a div:
<div class="scrollTarget">We will scroll to here</div>
Now we insert the "void" link where we need the scroll to be triggered by a click:
<a href"javascript:void(0)" onclick="scrollPageTo('.scrollTarget', 15)">Scroll to div</a>
We pass two parameters to the function: the first is our target and the "." or "#" is needed depending on the type of selector (class or ID) we used (in our case it's a class so "."). The second parameter is used to scroll to a position which is just 15 pixels above the target. The second parameter is optional, but it can be used to make the scroll as perfect as we need it.
The function has to be place in the head of our document:
<script type="text/javascript">
  function scrollPageTo(myTarget, topPadding) {
    if (topPadding == undefined) {
        topPadding = 0;
    var moveTo = $(myTarget).offset().top - topPadding;
    $('html, body').stop().animate({
        scrollTop: moveTo
    }, 1000);
I must say I've found the above snippet somewhere a long time ago and I can't remember where. I'm sure I've used it more than once in web pages and I have surely modified it somehow.

In any case, there we are.

Take care and see you next time!

1 comment:

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.