Scroll to change the background

Bit by bit. By opacity. Demo for https://toster.ru/q/309680

by Gleb Kemarsky

HTML

<div class="bg"></div>
<div class="bg-blue"></div>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>
<p>Scrool up and down to change the background.</p>

CSS

.bg, .bg-blue {
  height: 100%;
  left: 0;
  position: fixed;
  top: 0;
  width: 100%; 
}

.bg {
  background: orange;
  z-index: -4; 
}

.bg-blue {
  background: blue;
  z-index: -3; 
  opacity: 0; 
}

JavaScript

$(document).ready(function(){

	var $bg_blue = $('.bg-blue');
	var bg_state = null;
  var scroll_orange = 20;
  var scroll_blue = 420;

  $(window).scroll(function() {
		var scroll_current = $(this).scrollTop();
		if (scroll_current < scroll_orange) {
			if (bg_state != 'orange') {
				bg_state = 'orange';
				$bg_blue.stop().animate({
					opacity: 0
				});
			}
		} else if (scroll_current > scroll_blue) {
			if (bg_state != 'blue') {
				bg_state = 'blue';
				$bg_blue.stop().animate({
					opacity: 1
				});
			}
		} else {
      bg_state = null;
      $bg_blue.stop().animate({
			  opacity: (scroll_current - scroll_orange) / (scroll_blue - scroll_orange)
			});
		}
  });
    
});//jQuery