views:

643

answers:

3

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?

+6  A: 

Yep, even in plain javascript it's pretty easy. You give an element an id and then you can use that as a "bookmark":

<div id="here">here</a>

If you want it to scroll there when a user clicks a link, you can just use the tried-and-true method:

<a href="#here">scroll to over there</a>

To do it programmatically, use scrollIntoView()

document.getElementById("here").scrollIntoView()
nickf
@homestead: nickf's solution allows you to scroll to any "id" in the document. Mine is the plain old vanilla one.
o.k.w
+3  A: 

Here's a pure javascript version:

location.hash = '#123';

It'll scroll automatically. Remember to add the "#" prefix.

o.k.w
Using the primitive way of named anchor, you can have URL that includes the hash E.g. http://www.mywebsite.com/page-about/#123Bookmarking includes the hash + scrollintoview behaviour too.
o.k.w
+11  A: 

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/project/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>
Juraj Blahunka
+1 The lightweight approach is so cool, bravo!
jartaud