JSFiddle - React, Tailwind, and code Playground

by nabtron

HTML

<div id="sidebar">

</div>

CSS

#sidebar{
  height:100px;
  margin-top: 800px;
  margin-bottom: 1000px;
  background-color: red;
}

.sidebarscrollClass {
  background-color:green !important;
}

JavaScript

// Determine if an element is in the visible viewport
function isInViewport(element) {
  var rect = element.getBoundingClientRect();
  var html = document.documentElement;
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || html.clientHeight) &&
    rect.right <= (window.innerWidth || html.clientWidth)
  );
}


var didScroll = false;

window.onscroll = doThisStuffOnScroll;

function doThisStuffOnScroll() {
    didScroll = true;
		if( isInViewport(document.getElementById('sidebar')) ) {
			document.getElementById('sidebar').className = "sidebarscrollClass";
		}else{
			document.getElementById('sidebar').className = "";
    }
}

setInterval(function() {
    if(didScroll) {
        didScroll = false;
        console.log('You scrolled');
    }
}, 100);