Change background color class when in viewport
Based on element position within viewport, change background color via toggle of classes.
by Jon Fuller
HTML
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<body>
<div id="one" class="div">ONE</div>
<div id="two" class="div red-div change-bg-to-blue">TWO</div>
<div id="three" class="div">THREE</div>
<div id="four" class="div yellow-div change-bg-to-green">FOUR</div>
</body>
CSS
body {
background: #333333;
}
.div {
height: 100vh;
}
.div[class*="change-bg-to-"] {
transition: background-color 3s ease, color 3s ease;
transition-delay: 0.5s;
}
.red-div {
background: red;
}
.yellow-div {
background: yellow;
}
.blue-bg {
background: blue !important;
color: white !important;
}
.green-bg {
background: green !important;
color: white !important;
}
JavaScript
$(document).ready(function(){
$(window).scroll(function(){
if ($('.change-bg-to-blue').isOnScreen()) {
// The element is visible, do something
$('.change-bg-to-blue').addClass('blue-bg');
} else {
$('.change-bg-to-blue').removeClass('blue-bg');
}
if ($('.change-bg-to-green').isOnScreen()) {
// The element is visible, do something
$('.change-bg-to-green').addClass('green-bg');
} else {
$('.change-bg-to-green').removeClass('green-bg');
}
});
});
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};