Storm Blog

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);
    }
);

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>