How to scroll up or down the page to an anchor using jQuery?

function scroll_to_anchor(anchor_id){
    var tag = $("#"+anchor_id);
    $('html,body').animate({scrollTop: tag.offset().top},'slow');
}

Assuming that your href attribute is linking to a div with the tag id with the same name (as usual), you can use this code:

HTML

<a href="#goto" class="sliding-link">Link to div</a>

<div id="goto">I'm the div</div>

JAVASCRIPT - (Jquery)

$(".sliding-link").click(function(e) {
    e.preventDefault();
    var aid = $(this).attr("href");
    $('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});

Description

You can do this using jQuery.offset() and jQuery.animate().

Check out the jsFiddle Demonstration.

Sample

function scrollToAnchor(aid){
    var aTag = $("a[name='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

scrollToAnchor('id3');

More Information

  • jsFiddle Demonstration
  • jQuery.offset()
  • jQuery.animate()