Simple JavaScript page scroll

I was looking for a simple JavasCript page slider which scrolls the webpage a few pixels or to a label on the page. The ScrollTo jQuery solution was the first thing I found, which has many different ways to specify the target position. This is an elegant solution but I was looking for something simpler.

Click to scroll down

It is recommended to use the ScrollTo jQuery plugin if you want a more advanced solution where you can scroll to a DOM element, a label or a raw number. It has many options to customize the scrolling animation: axis, duration, easing, queue, margin and more.

I always try to keep the amount of included script files low so I had to come up with a very lightweight solution.

The simplest JavaScript command to scroll to a given position on the page is the scrollTo(xpos,ypos) but this doesn't have any animation. The reason I don't recommend to use this is because the visitor might get confused seeing a quick jump on the page not knowing what happened. A smooth scrolling effect is much fancier.

So if you don't want to include a new jQuery library on your webpage but still want to have a nice scrolling effect this is the solution I came up with which is so simple you can even write it inline in your html code.

The slider I'm presenting here scrolls a given distance on the page with the specified speed. You have to pass two variables to the function: yscroll shows how many pixels will the page be shifted and scrollspeed determines the slider speed.

The example given here scrolls down but of course you can scroll not only vertical but horizontal too making small changes on the code shown below.

function windowscroll(yscroll,scrollspeed){
    window.scrollBy(0,-9000);//initial scroll to the top of the page
    for (var iscroll=0;iscroll<yscroll;iscroll++){
        setTimeout('window.scrollBy(0,' + iscroll + ')',scrollspeed*iscroll);

If you want to save page loading time not including new JavaScript files you can write this code inline using the following snippet.

<div onClick="for (var iscroll=0;iscroll<35;iscroll++){setTimeout
('window.scrollBy(0,' + iscroll + ')',iscroll * 25);}">
Click here</div>

You can see this plugin in action on the Rubik's Cube Solver page clicking on the 'Generate image' button.



Back To The Top