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?
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});
})Thanks for the new lines of code. With the scroll function it works flawlessly.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside