Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Smooth Scroll to any Anchor [duplicate]

I have tried many different codes to smooth scroll to anchors. I can't find one that works. It needs to be able to scroll vertically, horizontally, and diagonally. Another problem I find with others is that they don't seem to work with multiple targets. I want it to be able to scroll to any anchor on the page without having to edit the script.

Fiddle

This is the code that matches this the closest, I cant get it to work:

var $root = $('html, body');
$('a').click(function () {

    $root.animate({

        scrollLeft: $($.attr(this, 'href')).offset().left,
        scrollTop: $($.attr(this, 'href')).offset().top

    }, 500);

    return false;
});

It works in JSFiddle but when I put it on my page it doesn't work.

Why is this not a duplicate? This is a multi-direction script that doesn't target single elements. It applies to all the links on the page.

like image 232
b2550 Avatar asked Aug 13 '13 04:08

b2550


1 Answers

I can't get your jsfiddle to work, see if this works:

$(function(){
    $('a').on({
      click:function (e) {
        e.preventDefault();
        var root = $("html, body");
        var target = $(this).attr("href");
        root.animate({  
            scrollLeft: $(target).offset().left,
            scrollTop: $(target).offset().top
        }, 500);
      }
    });
)};
like image 107
peterchon Avatar answered Oct 11 '22 05:10

peterchon