Skip to content

Instantly share code, notes, and snippets.

@ehynds
Created February 26, 2010 20:54
Show Gist options
  • Save ehynds/316145 to your computer and use it in GitHub Desktop.
Save ehynds/316145 to your computer and use it in GitHub Desktop.
// determine if an element is COMPLETELY inside the current viewport.
// surely, there must be an easier way
$.expr[':']['in-viewport'] = function(element){
var $win = $(window), $el = $(element),
// element calculations
offset = $el.offset(),
outerWidth = $el.outerWidth(),
outerHeight = $el.outerHeight(),
offsetLeft = offset.left + outerWidth,
offsetTop = offset.top + outerHeight,
// window calculations
winScrollTop = $win.scrollTop(),
winScrollLeft = $win.scrollLeft(),
winViewportTop = $win.height() + winScrollTop,
winViewportLeft = $win.width() + winScrollLeft;
// so... is it in the viewport?
return offsetLeft >= winScrollLeft
&& offsetLeft <= (winViewportLeft + outerWidth)
&& offsetTop >= winScrollTop
&& offsetTop <= (winViewportTop + outerHeight)
? true : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment