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.
Written by Phil Renaud
Related protips
3 Responses
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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ui
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#