JSFiddle - React, Tailwind, and code Playground
HTML
<div class="body">
<div class="container">
<div class="sidebar" id="sidebar">
Pooper scooper!
</div>
</div>
</div>
CSS
.container {
width: 200px;
height: 400px;
border: 1px dashed #FF0000;
position: relative;
float: left;
}
.sidebar {
position: fixed;
border: 1px solid #0000FF;
}
.bottom {
position: absolute;
bottom: 0px;
}
.body {
width: 100%;
min-height: 1600px;
border: 1px solid #00FF00;
}
JavaScript
$(window).on("scroll", function() { // When you scroll the window, do this function
updatePosition();
});
var tester = null;
function updatePosition() {
var sidebar = $("#sidebar"); // Set #sidebar to a variable called "sidebar"
if (tester == undefined) {
// Create a tester div to track where the actual div would be.
// Then we test against the tester div instead of the actual div.
tester = sidebar.clone(true).removeAttr("id").css({"opacity" : "0.5" }).insertAfter(sidebar);
}
// If the tester is below the div, make sure the class "bottom" is set.
if (testPosition(tester)) {
sidebar.addClass("bottom");
console.log("Add class");
}
else {
sidebar.removeClass("bottom");
console.log("remove class");
}
}
function testPosition(sidebar) {
console.log(sidebar.offset().top + " + " + sidebar.outerHeight() +" >= " + sidebar.parent().offset().top + " + " + sidebar.parent().outerHeight());
if (sidebar.offset().top + sidebar.outerHeight() >= sidebar.parent().offset().top + sidebar.parent().outerHeight()) return true;
return false;
}