views:

83

answers:

4

Id like to make browser to scroll page to given anchor, just by using javascript.

I have specified name or id attribute in my html code:

 <a name="anchorName">..</a>

or

 <h1 id="anchorName2">..</h1>

I'd like get same effect as you get by navigating to http://server.com/path#anchorName. The page should be scrolled so that the anchor is near top of visible part of page.

+1  A: 

Something as easy as should do the trick.

function jumpToAnchor(anchor){
     location.href = location.href+"#"+ anchor;
}

Another option would be to use the jQuery ScrollTo plugin.

ahsteele
I tried this and it works also.
Juha Syrjälä
@Juha glad it worked as well. :)
ahsteele
+4  A: 

You can use jQuerys .animate(), .offset() and scrollTop. Like

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

example link: http://jsbin.com/unasi3/edit

If you don't want to animate use .scrollTop() like

$(document.body).scrollTop($('#anchorName2').offset().top);

or javascripts native location.hash like

location.hash = '#' + anchorid;
jAndy
As far as creating a selector to find the `<h1 id="anchorName">` or an `<a name="anchorName">`, use `$('#'+hash+',a[name='+hash+']')` or slightly optimized `$(document.getElementById(hash) || 'a[name='+hash+']')` which will search for the element by id first, and resort to searching the a's only if one isn't found.
gnarf
+5  A: 
function scrollTo(hash) {
    location.hash = "#" + hash;
}

No jQuery required at all!

Dean Harding
I tried this and decided to use this. You were also the first and had shortest code.
Juha Syrjälä
A: 

Way simpler:

element_to_scroll_to = document.getElementById('anchorName2');
element_to_scroll_to.scrollIntoView();
Mandx