jQuery: Scroll to anchor when calling URL, replace browsers behaviour

bj. picture bj. · Dec 14, 2009 · Viewed 49.4k times · Source

I already know the jQuery plugin ScrollTo, but I didn't find any way up to now to realize the following:

The users gets to my site (by typing, NOT by clicking a link on my page) domain.com/bla.php#foo

and the anchor "#foo" exists. Now I want that the browser of the user does NOT automatically scroll to "#foo", instead I want to smoothly scroll so that the element '#foo' is about in the middle of the view and NOT on the absolute top position of the users view.

thanks so far!

Answer

Jan Jongboom picture Jan Jongboom · Dec 14, 2009

If you don't create the actual anchor foo, but rather create your anchor with an id like _foo (something like <a id="_foo">). You can handle the $(document).ready to achieve this.

Something like (pseudo code)

$(document).ready(function() { 
    var elem = $('#_' + window.location.hash.replace('#', ''));
    if(elem) {
         $.scrollTo(elem.left, elem.top);
    }
});