How can I lower the opacity of a background image from 1 to 0 and return from 0 to 1 and so on?

3

// find elements


var $window = $(window)
var $layer = $('#banner-message')
var $section = $('.section')

$(window).on('scroll', function() {




	var $windowScroll = $window.scrollTop()

	var $scroll = $windowScroll / 1000



		if ( $scroll <= 1 && $scroll > 0  ){

			 var alphaBg = 1 - ( $windowScroll / 1000 )

			 	$layer.css('opacity', alphaBg)
				console.log('DEC',alphaBg);


			}else if ( $scroll > 1   ){

					  var alphaBg = ( $windowScroll / 1000 ) -1

					  $layer.css('opacity', alphaBg)
 				   	console.log('INC',alphaBg);
				
			}





	});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
 background: url('https://unsplash.it/1500/750?image=1041');
  width: 100%;
  height:600px;
   display: block;
	 background-size: cover;
   z-index: -1;
   width: 100%;
   height: 100%;
   opacity: 1;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
		background-size: cover;
		background-repeat:no-repeat;
		background-attachment: fixed;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

.section{
  height:1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="banner-message">
 <div class="section"><</div>
 <div class="section"><</div>
 <div class="section"><</div>
</div>

I have an image of a plant in a fixed position ... When I scroll, I would like this image to go down from opacities from 1 to 0 and then continue with the scroll from 0 to 1 and so on ...

for now the image is lowered from 1 to 0 and returns from 0 to 1, but more than 1 will follow.

in this link is a demo of my code link

Thanks

    
asked by Mirko Aloisi 11.05.2018 в 15:52
source

1 answer

1

You just have to change the background transparency in the 'scroll' event. I leave you a very simple example without a background image, adapting it to background-image is relatively trivial:

let toTransparent= true;
let opacity=1;
$(window).on('scroll', function(){
  if (toTransparent) {
    opacity-=0.01;
    if (opacity<0.01) {
      toTransparent=false;
    }
  } else {
    opacity+=0.01;
    if (opacity>0.99) {
      toTransparent=true;
    }
  }
  $('#d').css('background-color','rgba(255,0,0,${opacity})');
  
})
div {
  height:500vh;
  width:50%;
  background-color: rgba(255,0,0,1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="d"></div>
    
answered by 11.05.2018 в 16:59