Skip to content

Instantly share code, notes, and snippets.

@skhilko
Last active August 29, 2015 14:05
Show Gist options
  • Save skhilko/a29e31b820565bb3a964 to your computer and use it in GitHub Desktop.
Save skhilko/a29e31b820565bb3a964 to your computer and use it in GitHub Desktop.
A collection of cross-browser snippets to serve as a reference guide for simple DOM tasks
/**
* The width of the viewport.
* Does not include the scroll bar.
*/
function viewportWidth () {
return document.documentElement.clientWidth;
}
/**
* The height of the viewport.
* Does not include the scroll bar.
*/
function viewportHeight () {
return document.documentElement.clientHeight;
}
/**
* The number of pixels that the viewport has been scrolled horizontally.
*/
function viewportScrollX () {
// scrollLeft is a workaround for IE(<9) and quirks mode
return (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
}
/**
* The number of pixels that the viewport has been scrolled vertically.
*/
function viewportScrollY () {
// scrollTop is a workaround for IE(<9) and quirks mode
return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
}
/**
* Test if an element is in the same x-axis section as the viewport.
*/
function inViewportX (el) {
var rect = el.getBoundingClientRect();
return rect.right >= 0 && rect.left <= viewportWidth();
}
/**
* Test if an element in the same y-axis section as the viewport.
*/
function inViewportY (el) {
var rect = el.getBoundingClientRect();
return rect.bottom >= 0 && rect.top <= viewportHeight();
}
/**
* Test if an element is visible in the viewport.
*/
function inViewport (el) {
var rect = el.getBoundingClientRect();
return rect.bottom >= 0 && rect.right >= 0 && rect.top <= viewportHeight() && rect.left <= viewportWidth();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment