Skip to content

Instantly share code, notes, and snippets.

@jbuncle
Last active January 25, 2017 19:59
Show Gist options
  • Save jbuncle/6f6185e88be875b2585e736a422c3f15 to your computer and use it in GitHub Desktop.
Save jbuncle/6f6185e88be875b2585e736a422c3f15 to your computer and use it in GitHub Desktop.
2 jQuery Plugins for detecting if an element is in the current viewport (visible from the current scroll positions).
/*!
* 2 jQuery Plugins for detecting if an element is in the current viewport (visible from the current scroll positions).
*
* $.isWithinViewport - for detecting if the element is fully in view
* $.inViewport - for detecting if the element is partially in view
*
* Copyright 2016 James Buncle
*
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function($) {
$.fn.isWithinViewport = function() {
var windowBox = getWindowBox();
var elementBox = getElementBox($(this));
return (elementBox.top >= windowBox.top)
&& (elementBox.right <= windowBox.right)
&& (elementBox.bottom <= windowBox.bottom)
&& (elementBox.left >= windowBox.left);
};
$.fn.inViewport = function() {
var windowBox = getWindowBox();
var $el = $(this).first();
var elementBox = getElementBox($el);
//Top or bottom in view
var topInView = elementBox.top >= windowBox.top && elementBox.top < windowBox.bottom;
var bottomInView = elementBox.bottom <= windowBox.bottom && elementBox.bottom > windowBox.top;
//Top or bottom outside of view
var insideVertical = elementBox.top < windowBox.top && elementBox.bottom > windowBox.bottom;
var verticalInView = topInView || bottomInView || insideVertical;
//AND
//Left of right in view
var leftInView = elementBox.left >= windowBox.left && elementBox.left < windowBox.left;
var rightInView = elementBox.right <= windowBox.right && elementBox.right > windowBox.left;
//Left and bottom
var insideHorizontal = elementBox.left <= windowBox.left && elementBox.right > windowBox.right;
var horizontalInView = leftInView || rightInView || insideHorizontal;
return verticalInView && horizontalInView;
};
function getWindowBox() {
var $el = $(window);
return {
top: $el.scrollTop(),
left: $el.scrollLeft(),
right: $el.scrollLeft() + $el.width(),
bottom: $el.scrollTop() + $el.height()
};
}
function getElementBox($el) {
return {
top: $el.offset().top,
left: $el.offset().left,
right: $el.offset().left + $el.outerWidth(),
bottom: $el.offset().top + $el.outerHeight()
};
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment