Last Updated: February 25, 2016
·
30.03K
· phil_renaud

Fade an element relative to scroll, in one line

Here's a neat jQuery trick to fade an element based on how far down the page you've scrolled (maybe you want an element to be fully visible when the user first encounters it, but become transparent as they move along):

$('h1').css({'opacity':( 100-$(window).scrollTop() )/100});

Where $('h1') is the element to be faded, and the first '100' can be adjusted to allow for distance down the page.

3 Responses
Add your response

Do you have an example? I copied the code but it doesn't work.
On http://api.jquery.com/scrollTop/ the demo shows "scrollTop:0". Is that correct or is there a problem with jQuery?

over 1 year ago ·

Hi gehwissenlos - this code should be placed within a scroll function,

On riotindustries.com for example, I'm doing this:

$(window).scroll(function(i){
    var scrollVar = $(window).scrollTop();
    $('section#about .inner').children('h2').css({'top': .7*scrollVar });
    $('section#about .inner').children('h2').css({'opacity':( 100-scrollVar )/100});
})
over 1 year ago ·

Thanks for the new lines of code. With the scroll function it works flawlessly.

over 1 year ago ·