JSFiddle - React, Tailwind, and code Playground
by Marian Rick
HTML
<div id="content">Scroll me long enough for 2000px</div>
<div id="mydiv" class="fixed">Hey there</div>
<div id="end">Everything has an end</div>
CSS
* {margin: 0; padding: 0; font-family: sans-serif; }
#content {
height: 2000px;
background: yellow;
}
#end {
height: 3000px;
background: blue;
}
#mydiv {
height: 50px;
width: 100%;
background: red;
}
.fixed {
position: fixed;
bottom: 0;
}
JavaScript
// Create function to add/remove Class if .scrollTop
$.fn.followTo = function (pos) {
var $this = this,
$window = $(window);
$window.scroll(function (e) {
if ($window.scrollTop() < pos) {
$this.addClass('fixed');
} else {
$this.removeClass('fixed');
}
});
};
var $height_content = $('#content').outerHeight(); //get height of content
var $height_div = $('#mydiv').outerHeight(); //get height of fixed div
var $height_viewport = $(window).height(); //get height of viewport
var $fixed_till = ($height_content + $height_div - $height_viewport);
// Use function created above like so:
// $('selector').followTo( /* height from top in px */ );
$('#mydiv').followTo($fixed_till);