JavaScript snippets

Evaluating JSON:

var obj = eval('(' + str + ')');

Detecting if someone is pressing ENTER (jQuery is used in the listing):

  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:''+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); 

Setting and unsetting/clearing a timeout:

twTimeout = setTimeout("displayTwitter()", 60000);
. . .

Reloading a window:


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&params='+encodeURI(params)+'&ref='+encodeURI(req[0]));