ade123 ade123 - 6 months ago 40
Javascript Question

Simple jQuery scroll to anchor up or down the page...?

I'm looking for a way to include a simple slide effect for when you click a link to a local anchor either up or down the page.

If possible i'd like something where you have a link like so:

<a href="#nameofdivetc">link text, img etc.</a>


perhaps with a class added so you know you want this link to be a sliding link:

<a href="#nameofdivetc" class="sliding-link">link text, img etc.</a>


Then if this link is clicked, the page simply slides up or down to the required place (could be a div, heading, top of page etc).

A bit like I used on this site of mine http://www.adriancrellin.co.uk/ , but this was a good while ago and I'm now doing it for a client and wondered if there are any better or simpler solutions out there.

Any ideas would be great!




This is what I had previously, can't remember where I got the code from exactly now, but it seems to work quite nicely, any better solutions would be great though :o)

$(document).ready(function(){
$(".scroll").click(function(event){
//prevent the default action for the click event
event.preventDefault();

//get the full url - like mysitecom/index.htm#home
var full_url = this.href;

//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
var parts = full_url.split("#");
var trgt = parts[1];

//get the top offset of the target anchor
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;

//goto that anchor by setting the body scroll top to anchor top
$('html, body').animate({scrollTop:target_top}, 1500, 'easeInSine');
});
});

Answer

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

Comments