javascript - Increase element opacity when user scrolls down the page -
i've seen lot of question related modifying element opacity when user scrolls haven't found 1 helps me way need. have tried several formulas , haven't been able achieve effect want.
i have header bg image, , inside div use overlay, , want darker , darker smoothly (opacity increase) while user scrolls down.
edit: desired effect is:
opacity default set 0.2 in css. when user starts scrolling down start increasing 0.2 1. when user scrolls again decrease 1 (or whatever value was) 0.2.
fiddle: https://jsfiddle.net/z7q2qtc6/
<div class='nice-header'> <div class='header-overlay'></div> </div>
css
.nice-header { position: relative; height: 300px; background: center center; background-size: cover; background-image: url(http://www.boeing.com/resources/boeingdotcom/commercial/787/assets/images/marquee-787.jpg); } .header-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgb(0,0,0); opacity: 0.2; }
js
$(window).scroll(function() { $('.header-overlay').css({ opacity: function() { var opacity = 0; //todo: //set opacity higer value whilst user scrolls return opacity; } }); });
you can retrieve current scrolling position using .scrolltop()
method.
to calculate opacity, subtract scrolltop value height of element , divide element's height.
$(window).scroll(function() { var scrolltop = $(this).scrolltop(); $('.header-overlay').css({ opacity: function() { var elementheight = $(this).height(); return 1 - (elementheight - scrolltop) / elementheight; } }); });
if want account element's initial opacity of 0.2
:
$('.header-overlay').css({ opacity: function() { var elementheight = $(this).height(), opacity = ((1 - (elementheight - scrolltop) / elementheight) * 0.8) + 0.2; return opacity; } });
Comments
Post a Comment