rxfefg
Last Updated: February 25, 2016
·
24.86K
· 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.

Say Thanks
Respond

3 Responses
Add your response

12205
62499dd880b01b03662cf197d210c1ac

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 ·
12206

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 ·
12210
62499dd880b01b03662cf197d210c1ac

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

over 1 year ago ·