jQuery logo

Smoothly scroll to an element without a jQuery plugin

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.

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 cybdG by Cory LaViska (@claviska) on CodePen.

About the author

Cory LaViska is a founder, web developer, and bootstrapper based in New Hampshire. His current focus is on Surreal CMS, an awesome SaaS content management service for web designers. Need to get in touch? You can connect with him on Twitter.