Smoothly scroll to an element without a jQuery plugin

January 22, 2010

You know that special effect where you click on a link and your browser smoothly scrolls down to the appropriate section of the page? Pretty slick, right? Here are a couple snippets so you can do the same thing on your own website.

Looking for a better CMS? How about one you don’t have to install? Inline editing, responsive interface, legendary support—we have it all. Try Surreal CMS for free!

Scroll to a specific element

Here’s how to programmatically scroll to any element on the page. If you’re using jQuery, you don’t need a plugin. It’s very simple:

$('html, body').animate({
    scrollTop: $("#target-element").offset().top
}, 1000);

This will scroll the page down to #target-element over a period of one second (1,000 milliseconds = 1 second).

Scroll to the selected anchor

You can take things a bit further and animate scrolling for all anchors on your page. The following snippet will watch for clicks on any link that points to an anchor and smoothly scroll down to it:

$('a[href^="#"]').on('click', function(event) {

    var target = $(this.href);

    if( target.length ) {
        event.preventDefault();
        $('html, body').animate({
            scrollTop: target.offset().top
        }, 1000);
    }

});

See it in action

See the Pen FEiax by Surreal CMS (@surrealcms) on CodePen.

comments powered by Disqus