Search code examples
javascriptjqueryscroll

Smooth scroll to div id jQuery


I've been trying to get a scroll to div ID jQuery code to work correctly. Based on another stackoverflow question I tried the following

DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/

$('#myButton').click(function() {
   $.scrollTo($('#myDiv'), 1000);
});

But it didn't work. It just snaps to the div. I also tried

$('#myButton').click(function(event) {
     event.preventDefault();
   $.scrollTo($('#myDiv'), 1000);
});

With no progress.


Solution

  • You need to animate the html, body

    DEMO http://jsfiddle.net/kevinPHPkevin/8tLdq/1/

    $("#button").click(function() {
        $('html, body').animate({
            scrollTop: $("#myDiv").offset().top
        }, 2000);
    });