Change the opacity of a scroll div

How can I make the next DIV disappear on top of the previous one when scrolling down the page?

I created this script to illustrate it better: http://jsfiddle.net/meEf4/176/
So, for example, if you are halfway down, the background is blue.

Edit: Here is the contents of this jsFiddle if it ever exploded and someone is stuck with a similar problem.

<style> html, body, #red, #green, #blue { height: 100%} #container { height: 300%} #red, #green, #blue { position: fixed; top: 0; width: 100%; } #red { background:red; z-index: 5} #blue { background:blue; z-index: 4} #green { background:green; z-index: 3}​ </style> <div id="container"> <div id="red"></div> <div id="blue"></div> <div id="green"></div> </div>​ 
+7
source share
2 answers

You can do it something like this:

 var target = $('div.background'); var targetHeight = target.height(); var containerHeight = $('#container').outerHeight(); var maxScroll = containerHeight - targetHeight; var scrollRange = maxScroll/(target.length-1); $(document).scroll(function(e){ var scrollY = $(window).scrollTop(); var scrollPercent = (scrollRange - scrollY%scrollRange)/scrollRange; var divIndex = Math.floor(scrollY/scrollRange); target.has(':lt(' + divIndex + ')').css('opacity', 0); target.eq(divIndex).css('opacity', scrollPercent); target.has(':gt(' + divIndex + ')').css('opacity', 1); });​ 

WORKING DEMO FIDDLE

You map the scroll value to the background of the div you should aim at using the maxScroll value divided by the number of background divs - 1 . This number is the scroll range that a single div background should cover. Then you calculate the scroll percentage for this div using the scroll value the scroll range module, so you get a value from 1 to 0 for the target div.

Then you set your target div to the computed value, the divs below have an opacity of 1, the divs above it have an opacity of 0 (because before they went their range from 1 to 0)

+7
source

This solution can be improved to make it more general, but it started

 $(document).ready(function() { var colordivs = $('#container div'); $(document).scroll(function(e) { var scrollPercent = ($(window).scrollTop() / $('#container').outerHeight()) * 100; if (scrollPercent > 0) { if (scrollPercent < 33) { var opacity = 1 - (scrollPercent / 33); $(colordivs[0]).css('opacity', opacity); } else if (scrollPercent > 66) { var opacity = 1 - (scrollPercent / 100); $(colordivs[0]).css('opacity', 0); $(colordivs[1]).css('opacity', 0); $(colordivs[2]).css('opacity', opacity); } else if (scrollPercent > 33) { var opacity = 1 - (scrollPercent / 66); $(colordivs[0]).css('opacity', 0); $(colordivs[1]).css('opacity', opacity); } } }); }); 
+1
source

All Articles