Last active
October 24, 2017 07:58
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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