Friday, May 29, 2020

Quick Tip: How to Create a Simple Fade Effect on Scroll

Quick Tip: How to Create a Simple Fade Effect on Scroll

In today’s super quick tutorial, we’ll learn how to build a simple, yet useful scroll effect. As we scroll within the page, the visibility of two elements will change depending on the scroll position.

As the saying goes: “a picture is worth a thousand words”, so let’s have a look at what we’re going to create (scroll down to see the effect):

1. Begin With the Page Markup

Similarly to the previous tutorial, we’ll define a section with a heading and a fullscreen div wrapper. The wrapper will include two empty divs. Both elements will have a background image. The last element will receive the front class.

Here’s the markup:


2. Add the CSS

As already discussed, the wrapper element will cover the full viewport height. Also, its  children will be stacked on top of one another. By default, the last element will appear.

The styles are as follows:


3. Animate on Scroll

As we start scrolling down, the .front element will gradually fade out and its sibling element will appear. Conversely, as we start scrolling up, the .front element will gradually fade in and thus sit on top of its sibling.

To accomplish this, we’ll first store in the checkpoint variable a number (change it according to your needs) which will determine after how many pixels the .front element should disappear. Then, we’ll listen for the scroll event and perform the following actions inside its callback:

  • Keep track of how much a user has scrolled vertically.
  • If the amount of their scrolling is less than the target number, the .front element will gradually become hidden or visible depending on the scrolling direction. Otherwise, for safety, we’ll set its opacity to 0.

Here’s the related JavaScript code:


You’ve Finished Your Simple Scroll Fade Effect!

Done! With just a few lines of code, we managed to create an interesting scroll effect that you can try, especially on the hero sections of your pages.

Hopefully, you enjoyed this small exercise and have taken inspiration for building something similar in an upcoming project. As a quick idea, instead of having two different images, you can combine this demo with the one from the previous tutorial and reveal the colored image.


As always, thanks a lot for reading!

More Scrolling Tutorials

Learn more about scrolling effects with these tutorials:


No comments:

Post a Comment