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.getAttribute('href'));

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


See it in action

See the Pen cybdG by Cory LaViska (@claviska) on CodePen.

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.