Skip to content

Scroll an element into view programmatically with JavaScript

I’ve just finished building an FAQ section for one of Storm‘s clients. The client requested that a list of questions be shown at the top of the page and the user be scrolled to the appropriate answer when they clicked the question. The site was using a URL re-writing scheme that meant using traditional #anchor links was impossible. We got around this by using a very simple piece of JavaScript.

document.getElementById('MyID').scrollIntoView(true);

This method will jump you straight to the top of the element with Id MyID. If you want to animate the scroll down the page, then a simple little bit of jQuery will give the right effect.

$("#my-link-id").click(
    function()
    {
        $('html:not(:animated), body:not(:animated)').animate({
            scrollTop: $("#scrollToHere").offset().top
        }, 2000);
    }
);