/blog/articles/

Gradually fade out element on scroll

A popular effect is to fade out an element when you start to scroll. You can do that by checking how far the user has scrolled and then perform a fade out animation and do the reverse if the users scrolls back up. But the effect gets even a little bit nicer if you gradually fade out the element according to how far the user has scrolled.

You can achieve this effect with just a few lines of jQuery.

First we store the element we want to animate in a variable we don't have to look for it on every scroll event.

var myElement = $('.js_my-element');

If the user scrolls we grab the scroll position and store it in variable.

$(window).on('scroll', function() {
    var st = $(this).scrollTop();

Then we update the opacity value on our element. For that we divide the scroll position by a value of our choice. A higher value means the user has to scroll a longer distance before the element has completely faded out. Then we subtract the result from 1 and apply the result as the new opacity value.

myElement.css({
    'opacity' : 1 - st/600
});

This is the complete code:

var myElement = $('.js_my-element');

$(window).on('scroll', function() {
    var st = $(this).scrollTop();
    myElement.css({
        'opacity' : 1 - st/600
    });
});
Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.