Skip to content

Instantly share code, notes, and snippets.

@vaidik
Created November 24, 2012 03:10
Show Gist options
  • Save vaidik/4138215 to your computer and use it in GitHub Desktop.
Save vaidik/4138215 to your computer and use it in GitHub Desktop.
Some utility script that I have used (at times) and might want to use later in my projects.
/**
* Checks if an object is empty or not.
*/
Object.prototype.isEmpty = function() {
for(var key in this) {
if (this.hasOwnProperty(key)) {
return false;
}
}
return true;
}
/**
* Converts native strings to strings in title case.
*/
String.prototype.toTitleCase = function() {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
/**
* Checks if an element is completely visible in browser's viewport or not.
*/
function elementInViewport(el) {
var rect = el.getBoundingClientRect()
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
)
}
/**
* Checks if any part of an element is visible in browser's viewport.
*/
function inViewport (el) {
var r, html;
if ( !el || 1 !== el.nodeType ) { return false; }
html = document.documentElement;
r = el.getBoundingClientRect();
return ( !!r
&& r.bottom >= 0
&& r.right >= 0
&& r.top <= html.clientHeight
&& r.left <= html.clientWidth
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment