<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="panel" data-color="white">
<div>
<h1>Magic scrolling colours</h1>
<p>Scroll to animate the background colour of the body as a full height panel becomes visible.</p>
<p>I have tried to comment the code, particurly the JavaScript, as much as possible. I hope it's clear to understand.</p>
<p>If you have any questions my twitter is <a href="https://twitter.com/daveredfern">@daveredfern</a>.</p>
</div>
</div>
<div class="panel" data-color="violet">
<h2>Violet panel</h2>
</div>
<div class="panel" data-color="indigo">
<h2>Indigo panel</h2>
</div>
<div class="panel" data-color="blue">
<h2>Blue panel</h2>
</div>
/* Setting fade transition and default settings */
body {
color: #000;
background-color: #fff;
transition: background-color 1s ease;
}
/* panel styles */
.panel {
/* min height incase content is higher than window height */
min-height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
font-family: sans-serif;
/* outline: 10px solid hotpink; */
/* turn above on to see the edge of panels */
}
/* colours */
.color-violet {
background-color: green;
}
.color-indigo {
background-color: #4332CF;
}
.color-blue {
background-color: red;
}
$(window).scroll(function() {
// selectors
var $window = $(window),
$body = $('body'),
$panel = $('.panel');
// Change 33% earlier than scroll position so colour is there when you arrive.
var scroll = $window.scrollTop() + ($window.height() / 1);
$panel.each(function () {
var $this = $(this);
// if position is within range of this panel.
// So position of (position of top of div <= scroll position) && (position of bottom of div > scroll position).
// Remember we set the scroll to 33% earlier in scroll var.
if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) {
// Remove all classes on body with color-
$body.removeClass(function (index, css) {
return (css.match (/(^|\s)color-\S+/g) || []).join(' ');
});
// Add class of currently active div
$body.addClass('color-' + $(this).data('color'));
}
});
}).scroll();