Scrolling Effects: Basics

by | Jun 15, 2018

Scrolling Effects: Basics

by | Jun 15, 2018 | Featured, Web Development, zveer

For this short article, I’m assuming that you’re familiar with the basics of JavaScipt, ( If not, here is  the link

While learning about JavaScript, you’ll be familiarized with Events and Event Handlers , (here is another link One of such events is the scroll event.



onscroll Event

The scrolling event in a browser is detected by the onscroll event attached to the browser window. Here is how you can implement this with JavaScript.

window.onscroll= function(){
      //some random code

The code inside this event handler runs every time someone scrolls through the window.

Here you can save the scroll position by saving the value of window.pageYOffset in a variable. We’ll be implementing some interesting effects using this variable in later articles.

For now, let’s just log it out in the console for now, (because why not)

window.onscroll= function(){



window.scrollTo() Method

Another important function/method to be mentioned here is the window.scrollTo()

This method takes two variables and scrolls the browser window to the position described by these variables. For example

window.scrollTo( 0, 200 );

This function scrolls the window by 0px horizontally and 200px vertically.




window.scrollBy() Method

This method helps you to scroll by a specific number of pixels. For example,

window.scrollBy( 0, 200 );

This scrolls the window by 200px in the vertical direction. This can also be used repeatedly to jump to different part of your website.

(please note that these functions do not animate the browser window and thus do not transition the scroll. The change in scrollbar position is abrupt and therefore not very pleasant. But, we will figure out how to make this work with a hack in a later article)

So what happens next?

I guess that’s all for this article, I’ll be back very soon with applications to these events and methods. There I will talk about creating parallax effects using these functions, we’ll make elements appear/disappear and much more. Until then, keep creating!




Submit a Comment

Your email address will not be published. Required fields are marked *

More from this Category