Search code examples
ajaxjquerysmooth-scrolling

JQuery scroll to anchor on click?


Basically I have this function is a class that creates pagination. I want to somehow use a smooth scroll to move the page back to the top of the comment container div but am unsure where or what function I would need to do that.

var Comments = function(options) {
    this.options = {
            id: 0,
            page: 0,
            object: null,
            name: null,
            parentid: 0,
            folder: './'
        };

    this.options = $.extend(this.options, options || {});  

    this.getComments =  function(page) {
        this.options.page = page;
        var object = this.options.object;
        var data = 'objid=' + this.options.name;
        $.ajax({
           type: "GET",
           url: this.options.folder + 'backend.php',
           data: data,
           success: function(msg){
             object.html(msg);
           }
         });
    };  

    this.getComments(this.options.page);
});

I'd like to get do something in the success getComments function that moves it up to the ID of the container. Is there a good way?


Solution

  • If your comment div has an ID of comment-div, then you can do this:

    $('html,body').animate({
        scrollTop: '+=' + $('#comment-div').offset().top + 'px'
    }, 'fast');
    

    You can adjust the speed as easing as needed, just check the animate documentation for details.