Skip to content

Instantly share code, notes, and snippets.

@hemant-tivlabs
Created December 19, 2019 11:05
Show Gist options
  • Save hemant-tivlabs/f82f35bffdb1f196cb49d84f65b5737d to your computer and use it in GitHub Desktop.
Save hemant-tivlabs/f82f35bffdb1f196cb49d84f65b5737d to your computer and use it in GitHub Desktop.
Constrained Floating HTML DIV - Stays fixed at the top when the page is scrolled down, but never goes out of the container
.has-constrained-float { position: relative; /* This container div should have a defined height of its own, that defines the range the floating child could travel. In general use, this could be a child of a flex parent, as that would automatically take the height of its sibling */ }
.constrained-float.fixed { position: fixed; top: 0 }
.constrained-float.absolute { bottom: 0; position: absolute; top: auto }
$(document).ready(function() {
$(window).scroll(function() {
$('.constrained-float').each(function(i, cf) {
var $cf = $(cf),
window_scroll_top = $(window).scrollTop(),
nav_class = '';
if($(window).width() > 991) {
if(window_scroll_top > $cf.parent().offset().top)
nav_class = 'fixed';
else
$cf.removeClass('fixed');
if($cf.parent().offset().top + $cf.parent().height() - $cf.height() < window_scroll_top)
nav_class = 'absolute';
else
$cf.removeClass('absolute');
$cf.addClass(nav_class);
} else
$cf.removeClass('fixed absolute');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment