How can I scroll to a specific location on the page using jquery?

mrblah picture mrblah · Oct 19, 2009 · Viewed 278.3k times · Source

Is it possible to scroll to a specific location on the page using jQuery?

Does the location I want to scroll to have to have:

<a name="#123">here</a>

Or can it just move to a specific DOM id?

Answer

Juraj Blahunka picture Juraj Blahunka · Oct 19, 2009

jQuery Scroll Plugin

since this is a question tagged with jquery i have to say, that this library has a very nice plugin for smooth scrolling, you can find it here: http://plugins.jquery.com/scrollTo/

Excerpts from Documentation:

$('div.pane').scrollTo(...);//all divs w/class pane

or

$.scrollTo(...);//the plugin will take care of this

Custom jQuery function for scrolling

you can use a very lightweight approach by defining your custom scroll jquery function

$.fn.scrollView = function () {
    return this.each(function () {
        $('html, body').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    });
}

and use it like:

$('#your-div').scrollView();

Scroll to a page coordinates

Animate html and body elements with scrollTop or scrollLeft attributes

$('html, body').animate({
    scrollTop: 0,
    scrollLeft: 300
}, 1000);

Plain javascript

scrolling with window.scroll

window.scroll(horizontalOffset, verticalOffset);

only to sum up, use the window.location.hash to jump to element with ID

window.location.hash = '#your-page-element';

Directly in HTML (accesibility enhancements)

<a href="#your-page-element">Jump to ID</a>

<div id="your-page-element">
    will jump here
</div>