JSFiddle - React, Tailwind, and code Playground
by rlemon
HTML
<br><br><br><br><br><br>
<div id="foo" class="foo"></div>
<p class="long">scroll</p>
CSS
.foo {
position: relative;
height: 100px;
width: 100px;
background-color: red;
}
.sticky {
position: fixed;
top: 0px;
left: 0px;
}
.long { height: 3000px; }
JavaScript
var foo = document.getElementById('foo');
document.onscroll = function(e) {
if (document.body.scrollTop > foo.offsetTop) {
foo.className = "foo sticky";
} else {
if (foo.className.indexOf('sticky')) {
foo.className = "foo";
}
}
};