I'm trying to get the total number of a given html element's pixels which are visible inside the viewport. This question and accepted answer Can I detect the user viewable area on the browser? were very useful for determining whether the element is in view/out of view/partially in view, but for the partially in view case I need to get the total (vertical x horizontal) number of pixels not obscured by the viewport. I was trying something like this, but the horizontal value is always wrong:
var $element = $(element),
pos = $element.offset(),
elemLeft = pos.left,
elemTop = pos.top,
elemHeight = $element.outerHeight(),
elemWidth = $element.outerWidth(),
winLeft = $(top).scrollLeft(),
winTop = $(top).scrollTop(),
winHeight = $(top).height(),
winWidth = $(top).width(),
nElemTotalPx = elemWidth*elemHeight,
nElemTotalPxInView,
nVpxInView = elemHeight,
nHpxInView = elemWidth;
//obscured by bottom of window
if(winTop > elemTop){
nVpxInView = (elemTop+elemHeight)-winTop;
//obscured by top of window
}else if(winHeight-winTop > elemTop){
nVpxInView = (winTop+winHeight)-elemTop;
};
//obscured by left of window
if(winLeft > elemLeft){
nHpxInView = (elemLeft+elemWidth)-winLeft;
//obscured by right of window
}else if(winWidth-winLeft < elemLeft+elemWidth){
nHpxInView = elemWidth-( elemWidth-(winWidth-winLeft) );
};
nElemTotalPxInView = nVpxInView*nHpxInView;
return nElemTotalPxInView;
Any help much appreciated!
My friend found another method to solve the problem. Setting 6 values each for both viewport and element means we can always calculate the percentage of pixels in view with a single equation: