Question

I have an image that I will use as the button. I need some code that will make the page scroll smoothly down 400px every time the image is clicked.

I think JQuery or Javascript would do the trick, I am not really sure because I do not know them.

It would be even better in fact, if instead of button, I could just have a keyboard shortcut. Just like Google on Google+, "J" and "K" are used to move up and down the posts. This is exactly what I am trying to achieve. Every post in my site will be the same height so that might make it easier to code.

Was it helpful?

Solution

Just bind an animate function to the click event of your image or button and let it animate the scrollTop property with 400.

For example, place this button on your page:

<input type="button" value="Scroll" id="scroll" />

And use this piece of JavaScript:

$('#scroll').click(function() {
    $('body').animate({scrollTop: +400}, 1000);
})

Just make sure jQuery is loaded and it will work.

Load jQuery by adding this just before the body end tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

And the best way to include the JavaScript snippet is to place the following between the script rule above and the body end tag.

<script type="text/javascript">
$(document).ready(function() {
    $('#scroll').click(function() {
        $('body').animate({scrollTop: +400}, 1000);
    })
});
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top