JqueryNo Comments

default thumbnail

If you want to smoothly transition and change background color while scrolling, preferably using just CSS and jquery then you are at right place.

HTML

<body>

    <div data-color="red" class="panel home">
        <div class="logo-zoom animate__animated animate__zoomIn">
	    <img src="img/logo-home.svg" alt="Logo Vilson">
	</div>
    </div>
    <div class="featured-wrapper panel" data-color="white">
	<div class="container">
	    <div class="row">
	        <div class="col-md-12">
		    <p>Test is a dummy test. </p>
		</div>
	    </div>
        </div>
   </div>

You need to add .panel class and data-color=” ” in main div of every section.

CSS

.color-white{
  background-color: #fff;
}
.color-red{
  background-color: #C1272D;
}

.color-gray{
  background-color: #F4F4F4;
}

You can create the background classes according to your need.

Jquery

$(window).scroll(function() {
  
  // selectors
  var $window = $(window),
      $body = $('body'),
      $panel = $('.panel');
	  
  var scroll = $window.scrollTop() + ($window.height() / 2);
 
  $panel.each(function () {
    var $this = $(this);
    
    if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) {
          
      $body.removeClass(function (index, css) {
        return (css.match (/(^|\s)color-\S+/g) || []).join(' ');
      });
       
      $body.addClass('color-' + $(this).data('color'));
    }
  });    
  
}).scroll();

We have tested the above code. You can try it.

Be the first to post a comment.

Add a comment