How to do a smooth scroll to an element/div with jquery

I was looking for a neat way to load dynamic data and then scroll the user to it. I wanted it to look smooth as well. Quick jumps make it look too harsh, like a page refresh.

Here is a simply function you can use. Just pass an element to it, jquery wrapped.

function…..

[javascript]
     function scrollToElement(ele) {
            var position = ele.position();
            $('html, body').stop().animate({
                scrollTop: position.top
            }, 500);
        }
[/javascript]

usage.

<div id=’foo’/>

You want to scroll to foo.

scrollToElement($(‘#foo’));

that easy.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *