Skip to content

Instantly share code, notes, and snippets.

@unsetbit
Created March 9, 2013 03:14
Show Gist options
  • Save unsetbit/5122323 to your computer and use it in GitHub Desktop.
Save unsetbit/5122323 to your computer and use it in GitHub Desktop.
get visible area
function getVisibleAreaHelper(container, maxBounds){
var bounds = container.getBoundingClientRect(),
visibleAreaTop = Math.max(bounds.top, maxBounds.top),
visibleAreaBottom = Math.min(bounds.bottom, maxBounds.bottom),
visibleAreaLeft = Math.max(bounds.left, maxBounds.left),
visibleAreaRight = Math.min(bounds.right, maxBounds.right);
//console.log(container, bounds.top, maxBounds.top);
if(visibleAreaBottom - visibleAreaTop < 1) return null;
if(visibleAreaRight - visibleAreaLeft < 1) return null;
return {
top: visibleAreaTop,
bottom: visibleAreaBottom,
right: visibleAreaRight,
left: visibleAreaLeft
};
}
function getPageOffset(element){
if(element === window) return [0, 0];
var container,
offsetTop = element.offsetTop
offsetLeft = element.offsetLeft;
while(container = element.offsetParent){
offsetTop += container.offsetTop;
offsetLeft += container.offsetLeft;
}
return [offsetTop, offsetLeft];
};
function paintVisibleArea(element){
var current = $(".paint");
if(current.length > 0) current.detach();
var boundingRect = element.getBoundingClientRect();
var offset = getPageOffset(element);
console.log(offset);
var visibleArea = {
top: boundingRect.top + offset.top,
left: boundingRect.left + offset.left
};
if(visibleArea == null) return;
var paint = $('<div class="paint" style="position:absolute; opacity:.25; z-index:1000; background-color:aqua; border:1px solid blue;"></div>');
paint.css({
top: offset.top + "px",
left: offset.left + "px"
});
paint.width(boundingRect.width);
paint.height(boundingRect.height);
$("body").append(paint);
}
$('body').click(function(e){
e.target.getBoundingClientRect();
paintVisibleArea(e.target);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment