2

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

4

2 Answers 2

2
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

Sign up to request clarification or add additional context in comments.

4 Comments

that sorta works. except that when I click it a second time it doesn't do anything. any idea what I'm doing wrong?
@user_1845661 add .stop() before .animate I've updated my answer
Thanks a lot! That did exactly what I wanted.
@user_1845661 Good :) I've updated it again, now you can even use negative values, to scroll in reverse direction...
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.