Question

I'm working on a one page website and would like to include named anchors across it for each section.

I also would like it so when you click a hyperlink on the navigation, it scrolls down/up the page smoothly rather than a quick jump.

What is the simplest copy and paste type jQuery script that I could use?

Thanks

Was it helpful?

Solution

this is a quick little script that should do the trick:

replace a with the selector of your links in the navigation. I've found scrolling body, html makes the scrolling a lot smoother

$('.nav_item').click(function(e){
    e.preventDefault(); //used to prevent default actions
    var _this = $($(this).attr('href'));
    $('body, html').animate({
        scrollTop: _this.offset().top
    }, 400) // how ever fast you want it to scroll.

});

OTHER TIPS

this is not a really exact script. If htere's a complete link in 'href' attribute (for example, htref="http://kremlin.ru/#putin" (and not just #putin) ) then the script won't work! In order the script could work with any type of links in href, you need to parse the attribute and delete everything that if BEFORE the mark '#' Here is the completely working one:

$(".scroll").click(function(e){
       e.preventDefault(); //used to prevent default actions
    var linker = $(this).attr('href');
    var linkerN=linker;
        linkerN=linkerN.replace(/^.*\#/, '');
        // alert(linkerN);
     if(linker.indexOf('#') > 0){

        $('body, html').animate({
        scrollTop: $('a'+'[name='+linkerN+']').offset().top}, 400);
    }
    else{
    //alert ('no "#" in link, going to go to:'+linker);
    window.location.href=linker;
   }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top