Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active October 24, 2017 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willbroderick/7822018 to your computer and use it in GitHub Desktop.
Save willbroderick/7822018 to your computer and use it in GitHub Desktop.
Emulate position:fixed on a div to keep it locked, vertically, inside the browser viewport. Designed for tiny sidebar-style content.Add class 'bump-me-down' to any floated div & it'll add padding to the top to make it fit.
/// Bump-down a div to fit (position:fixed style) inside a browser
$(function(){
if($('.bump-me-down').length > 0) {
$(window).on('scroll process-bump-me-downs resize', function(){
var scrollTop = $(window).scrollTop();
var defaultPad = 20;
$('.bump-me-down').each(function(){
var thisOffset = $(this).offset().top;
if($(this).data('bumpOffset')) {
thisOffset -= $(this).data('bumpOffset');
}
var thisHeight = $(this).outerHeight(true);
if(scrollTop > thisOffset - defaultPad) {
var parentHeight = $(this).parent().height();
var desiredPad = defaultPad + (scrollTop - thisOffset);
var maxPad = parentHeight - thisHeight;
var offsetToSet = Math.round(Math.min(desiredPad, maxPad));
$(this).addClass('is-bumped').data('bumpOffset', offsetToSet).css('transform', 'translateY(' + offsetToSet + 'px)');
} else {
$(this).filter('.is-bumped').removeClass('is-bumped').data('bumpOffset', 0).css('transform', '');
}
});
}).trigger('process-bump-me-downs');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment