Skip to content

Instantly share code, notes, and snippets.

@Inzman
Created March 14, 2019 07:31
Show Gist options
  • Select an option

  • Save Inzman/4bfdbd17a47a37b17396e58426a33690 to your computer and use it in GitHub Desktop.

Select an option

Save Inzman/4bfdbd17a47a37b17396e58426a33690 to your computer and use it in GitHub Desktop.
Get element percent in viewport
_getPercentInView = function(element){
$element = $(element);
var pos = $element.offset(),
theViewport = {top:null, left:null, bottom:null, right:null, width:null, height:null},
theElement = {top:null, left:null, bottom:null, right:null, width:null, height:null},
elemLeft = pos.left,
elemTop = pos.top,
elemHeight = $element.height(),
elemWidth = $element.width();
theViewport.width = $(window).width();
theViewport.height = $(window).height();
theViewport.top = $(window).scrollTop();
theViewport.left = $(window).scrollLeft();
theViewport.bottom = theViewport.top+theViewport.height;
theViewport.right = theViewport.left+theViewport.width;
theElement.top = elemTop - theViewport.top;
theElement.left = elemLeft - theViewport.left;
theElement.width = elemWidth;
theElement.height = elemHeight;
theElement.bottom = theElement.top+theElement.height;
theElement.right = theElement.left+theElement.width;
var nPercentInView = Math.round(100 * ((theElement.height-(Math.max(0,0-theElement.top) + Math.max(0,theElement.bottom-theViewport.height))) / theElement.height) * ((theElement.width-(Math.max(0,0-theElement.left) + Math.max(0,theElement.right-theViewport.width))) / theElement.width) );
return nPercentInView;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment