Skip to content

Instantly share code, notes, and snippets.

@ps-team
Created October 27, 2017 08:04
Show Gist options
  • Save ps-team/3df72e4b06c29c2d1d2297747d5247a8 to your computer and use it in GitHub Desktop.
Save ps-team/3df72e4b06c29c2d1d2297747d5247a8 to your computer and use it in GitHub Desktop.
JQuery plugin to vertically scroll view into first first parent that has scrolling available (css overflow set to either "auto", "scroll" and content > height). Interface: jQuery.scrollTo(elem, speed); //scroll this to elem in view jQuery.scrollIntoView(speed); //scroll this to first scroll-able parent
!(function($, window, d) {
'use strict';
var debug = false;
var defaultSpeed = 500;
$.fn.scrollTo = function(elem, speed) {
var elemTop = $(elem).offset().top - $(this).offset().top;
var thisScrollTop = $(this).scrollTop();
var targetScrollTop = thisScrollTop + elemTop;
var intViewportHeight = window.innerHeight;
var needToScroll = elemTop > intViewportHeight || elemTop < 0;
debug && console.log(elemTop, intViewportHeight);
debug && console.log("need to scroll", needToScroll);
if (needToScroll) {
$(this).animate({
scrollTop: targetScrollTop
}, speed === undefined ? defaultSpeed : speed);
}
return this;
};
$.fn.scrollIntoView = function(speed) {
//find overflowing parent
var parent = findScrollableParent(this[0]);
$(parent).scrollTo(this, speed === undefined ? defaultSpeed : speed);
return this;
};
//https://github.com/iamdustan/smoothscroll/blob/master/src/smoothscroll.js
/**
* finds vertical scrollable parent of an element
* @method findScrollableParent
* @param {Node} el
* @returns {Node} el
*/
function findScrollableParent(el) {
do {
debug && console.log(el);
el = el.parentNode;
} while (el !== d.body && !(el.clientHeight < el.scrollHeight && hasScrollingEnabled(el)));
debug && console.log("findScrollableParent");
debug && console.log(el);
return el;
}
function hasScrollingEnabled(el) {
debug && console.log("check overflow set");
var enabledOverflow = isOverflowToScrollEnabled(el, 'overflow') || isOverflowToScrollEnabled(el, 'overflow-y');
debug && console.log(enabledOverflow);
return enabledOverflow;
}
function isOverflowToScrollEnabled(el, overflowProperty) {
return $(el).css(overflowProperty).toLowerCase() == "auto" || $(el).css(overflowProperty).toLowerCase() == "scroll";
}
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment