Ask HN: What is your favorite Javascript code snippet?
Any useful gems or ways to overcome common hurdles? Would love to see and compare insights. Preferably framework/library agnostic if possible.
Quick and easy browser sniff:
var browser = (function x(){})[-5]=='x'
? 'ff3' : (function x(){})[-6]=='x'
? 'ff2' : /a/[-1]=='a'
? 'ff' : '\v'=='v'
? 'ie' : /a/.__proto__=='//'
? 'safari' : /s/.test(/a/.toString)
? 'chrome' : /^function \(/.test([].sort)
? 'opera' : 'Unknown';
Round to Nearest Multiple var roundThis = 54;
var closest = Math.round(parseInt(roundThis)/20)*20;
// output = 60
URL Paramaters var parts = window.location.search.substr(1).split("&");
var params = {};
for (var i = 0; i < parts.length; i++) {
var temp = parts[i].split("=");
params[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
}
console.log(params);
URL Hash Paramaters console.log(window.location.hash.substr(1).split("&")); var bind = function(func, context) {
var slice = Array.prototype.slice;
var args = slice.call(args, 2);
return function() {
return func.apply(context || {}, args.concat(slice.call(arguments)));
};
};