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)
Asciiom
source share