JavaScript snippets
Evaluating JSON:
var obj = eval('(' + str + ')');
Detecting if someone is pressing ENTER (jQuery is used in the listing):
$container.find("input").keydown(function(event){
if(event.keyCode == 13)
saveText($container, $(this));
});
Often when creating interfaces with jQuery I end up using something like “key-id” for elements, then the following function is handy for quickly getting just the id part:
function getId(el, sep){
sep = sep == '-' ? sep : '_';
var arr = el.attr('id').split(sep);
return arr[1];
}
Opening in a new window/popup:
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
Going to a new url in the parent window that opened the current window executing the code:
function openInParent(url){
window.opener.location.href = url;
}
Getting the current domain:
newArray = window.location.href.match(/^http:\/\/[^\/]+/gi);
alert(newArray[0]);
Setting and unsetting/clearing a timeout:
twTimeout = setTimeout("displayTwitter()", 60000);
. . .
clearTimeout(twTimeout);
Reloading a window:
window.location.reload();
Analytics tracking:
(function () {
var req = document.referrer.split('?');
var body = document.getElementsByTagName('body')[0];
var img = document.createElement('img');
var params = req[1].split(/[\?&=]/).join('|');
img.setAttribute('src', 'http://localhost:8090/req?acc=1¶ms='+encodeURI(params)+'&ref='+encodeURI(req[0]));
body.appendChild(img);
})();