Skip to content

Instantly share code, notes, and snippets.

@tadeaspetak
Last active April 20, 2017 07:38
Show Gist options
  • Save tadeaspetak/b9a0ec5287b5832dd522818d75bf0e4c to your computer and use it in GitHub Desktop.
Save tadeaspetak/b9a0ec5287b5832dd522818d75bf0e4c to your computer and use it in GitHub Desktop.
DOM utility functions.
// document body dimensions (exluding scrollbars)
export function getBodyDimensions() {
return {
width: document.body.clientWidth,
height: document.body.clientHeight
};
}
// client offset (typically non-existent)
export function getClientOffset() {
return {
top: document.documentElement.clientTop || document.body.clientTop || 0,
left: document.documentElement.clientLeft || document.body.clientLeft || 0
};
}
// get element coords, relative to the document
export function getCoords(element) {
const bounds = element.getBoundingClientRect();
const offset = getClientOffset();
const scroll = getScroll();
return {
top: Math.round(bounds.top + scroll.top - offset.top),
right: Math.round(bounds.right + scroll.left - offset.left),
bottom: Math.round(bounds.bottom + scroll.top - offset.top),
left: Math.round(bounds.left + scroll.left - offset.left)
};
}
export function getPixelDensity() {
return window.devicePixelRatio || 1;
}
// document sroll info
export function getScroll() {
return {
top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop,
left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft
};
}
// width & height of the viewport (i.e. window, including scrollbars)
export function getViewport() {
return {
width: window.innerWidth,
height: window.innerHeight
};
}
export function requestFullscreen(element) {
return (
element.requestFullscreen ||
element.mozRequestFullScreen ||
element.webkitRequestFullScreen ||
element.msRequestFullscreen
).bind(element)();
}
export function exitFullscreen() {
return (
document.exitFullscreen ||
document.mozExitFullScreen ||
document.webkitExitFullscreen ||
document.msExitFullscreen
).bind(document)();
}
export function isFullscreen() {
return (
document.fullscreenElement ||
document.mozFullscreenElement ||
document.webkitFullscreenElement ||
document.wsFullscreenElement
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment