user1845661
user1845661

Reputation: 127

Animated javascript scrollBy

I have a next button that when clicked I want it to scroll down the page 517px.

Using the following code (which I have found on another site) I have made a button that does that but I would like it to scroll in a smooth animated way. What would I need to add to do that?

The code I am using is a follows:

function scrollByPixels(x, y)
{
  window.scrollBy(x, y);
}

and the following on the actual button:

onclick="javascript:scrollByPixels(0, 517)"

Thanks in advance

Upvotes: 2

Views: 4049

Answers (2)

yckart
yckart

Reputation: 33408

function scrollByPixels(x, y) {
  $('html,body').stop().animate({
    scrollLeft: '+=' + x,
    scrollTop: '+=' + y
  });
}

...or as a simple plugin:

$.fn.scrollBy = function(x, y){
    return this.animate({
        scrollLeft: '+=' + x,
        scrollTop: '+=' + y
    });
};

demo

Upvotes: 2

redolent
redolent

Reputation: 4259

To scroll the whole window:

var value = $("#scrollToHere").offset().top;

$('html, body').animate({
        scrollTop: value
    }, 800);

Source: http://blog.alaabadran.com/2009/03/26/scroll-window-smoothly-in-jquery/

Upvotes: 1

Related Questions