Skip to content

Instantly share code, notes, and snippets.

@bekzod
Created March 22, 2016 12:13
Show Gist options
  • Save bekzod/8352c7f0766466e5793a to your computer and use it in GitHub Desktop.
Save bekzod/8352c7f0766466e5793a to your computer and use it in GitHub Desktop.
export function showInViewPort($el, tolarance, cb) {
if (!$el || !$el[0]) { return cb && cb(); }
tolarance = tolarance || 0;
var $body = $(document.body);
var topScrollAmount = $body.scrollTop();
var viewPortHeight = $(window).height();
var elY = $el.offset().top;
var elBottomY = elY + $el.height();
var topBounds = topScrollAmount + tolarance;
var bottomBounds = topScrollAmount + viewPortHeight - tolarance;
if (topBounds > elY) {
$body.animate({ scrollTop: topScrollAmount - (topBounds - elY) }, 300, cb);
} else if (bottomBounds < elBottomY) {
$body.animate({ scrollTop: topScrollAmount + (elBottomY - bottomBounds) }, 300, cb);
} else if (cb) {
cb();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment