Scroll to ID – JavaScript and jQuery

When you have internal page links (anchor links) and you want a nice scroll effect instead the harshness of just the immediate jump-to that internal links give you, use some fun jQuery to get er done.

// scroll to ID

$(“a”).click(function() {
var URL = $(this).attr(“href”); // get the URL of the a tag you clicked on
if (URL.substring(0, 1) == ‘#’) // check for the hash # character at the beginning of the URL
{        URL = URL.substring(1); // get the URL without the hash #
if(URL == ‘top’){$(‘html,body’).animate({scrollTop: 0},’slow’);} // scrolls to the top if the URL is ‘top’
else
{
var aTag = $(“span[id='”+ URL +”‘]”);
// this matches the URL with a span tag ID. You can of course change SPAN to DIV, P, etc.
$(‘html,body’).animate({scrollTop: aTag.offset().top},’slow’);
}
}
else return;
return false;
});
It's only fair to share...Tweet about this on TwitterShare on FacebookEmail this to someoneShare on Google+
This entry was posted in JavsScript, jQuery and tagged , , , . Bookmark the permalink.