Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

jQuery namespaced event binding/unbinding

// from a comment by Steven Bristol on errtheblog.com

I just wanted to share a really killer event handling tidbit:

Generally you do something like:

jQuery(’.class’).click(function(){//whatever});


Everyone knows this can be rewritten as:

jQuery(’.class’).bind(‘click’, function(){//whatever});


But sometimes you need to unbind something:

jQuery(’.class’).unbind(‘click’, function(){//});


The problem with this is that it will unbind all the click events, not just yours. So if multiple bits of javascript have a click event handler for ’.class’, unbinding removes them all. (This is because there is no way to identify an anonymous function.)

But jQuery is so good that there is a way to handle this: Namespacing your events:

jQuery(’.class’).bind(‘click.namespace’, function(){//}); 
jQuery(’.class’).unbind(‘click.namespace’);


or for reinitializing an element added via ajax:

jQuery(’.class’)unbind(‘click.namespace’).bind(‘click.namespace’, function(){//});

jQuery and Rails' respond_to

// Just throw this at the bottom of your application.js and you’re good to go: all jQuery ajax requests will trigger the wants.js block of your respond_to declaration, exactly like you’d expect. Enjoy.
// via: http://ozmm.org/posts/jquery_and_respond_to.html

jQuery.ajaxSetup({beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”,text/javascript”)} })

Javascript Bookmarklets

// various bookmarklets for cloning

javascript:var d=document,f='http://www.facebook.com/share',l=d.location,e=encodeURIComponent,p='.php?src=bm&v=4&i=1190041327&u='+e(l.href)+'&t='+e(d.title);1;try{if(!/^(.*\.)?facebook\.[^.]*$/.test(l.host))throw(0);share_internal_bookmarklet(p)}catch(z){a=function(){if(!window.open(f+'r'+p,'sharer','toolbar=0,status=0,resizable=0,width=626,height=436'))l.href=f+p};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else{a()}}void(0)


javascript:location.href='http://rickrolldb.com/entries/new?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title);

JS Regex's for sourcecode

Extracted from SyntaxHilighter

	MultiLineCComments : new RegExp('/\\*[\\s\\S]*?\\*/', 'gm'),
	SingleLineCComments : new RegExp('//.*$', 'gm'),
	SingleLinePerlComments : new RegExp('#.*$', 'gm'),
	DoubleQuotedString : new RegExp('"(?:\\.|(\\\\\\")|[^\\""\\n])*"','g'),
	SingleQuotedString : new RegExp("'(?:\\.|(\\\\\\')|[^\\''\\n])*'", 'g')

Center a DOM element, prototype based

Generally used to center a dialog (a div element).
Usage:
Position.Center(dialog);
The element can also be centered relatively to another node by using the parent parameter.
It requires the this snippet

Position.Center = function(element, parent) {
        var w, h, pw, ph;
        var d = Element.getDimensions(element);
        w = d.width;
        h = d.height;
        Position.prepare();
        if (!parent) {
                var ws = Position.GetWindowSize();
                pw = ws[0];
                ph = ws[1];
        } else {
                pw = parent.offsetWidth;
                ph = parent.offsetHeight;
        }
        element.style.top = (ph/2) - (h/2) -  Position.deltaY + "px";
        element.style.left = (pw/2) - (w/2) -  Position.deltaX + "px";
}

Prototype-based javascript window dimensions

Usage:
var dim = Position.GetWindowSize();
dim[0] is the window width
dim[1] is the window height

window can be specified, useful if you work with frames..

Position.GetWindowSize = function(w) {
        w = w ? w : window;
        var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
        var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
        return [width, height]
}

Prototype based Javascript min(...), max(...) functions


Use cases
min(1,-1,2,3,4) == -1
max(2,10) == 10

function min() {
 return $A(arguments).min();
}

function max() {
 return $A(arguments).max();
}

Physics quantities

// Physics quantities
// needs:<script src=gnmath.txt></script>
// needs: <script src=gnrandom.txt></script>
// ******************************************************************************
// ******************************************************************************
// ******************************************************************************
// ******************************************************************************
// Unit of Misur CLASS (UM) ***************************************
// an element is a string like m^2 k^3 s^(-1)
// its rappresentatios is:  [["m",2],["k",3],["s",-1]]
// (using gnmath constants definition we can also use: [[_m,2],[_k,3],[_s,-1]]
function UM(zxc){ 
	this.vv=zxc;
}
new UM([['dummy',0]]);


UM.prototype.toString=function(){
	this.collect();
	s=""
	for (var i=0;i<this.vv.length;i++){
		s+=' '
		s+=this.vv[i][0];
		s+=(this.vv[i][1]!=1)? '<sup>'+this.vv[i][1]+'</sup> ': ' '
	}
	return s;
}


	// +++++++++++ make the nth power of um
UM.pow=function(umis,n){// umis : is a UM!!
//	wwl('inUM.pow azsx='+azsx)
	for (var i=0;i<umis.vv.length;i++){
		umis.vv[i][1]*=n; // the name rest the same,the exponent is multiplied
	}
//	wwl('inUM.pow prima di uscire azsx='+azsx)

	return umis;
}




	// +++++++++++ collect same units
UM.prototype.collect=function(){
//	alert('collecting:'+this.vv)
	for (var i=0;i<this.vv.length;i++){
		for (var j=i+1;j<this.vv.length;j++){
			if(this.vv[i][0]==this.vv[j][0]){
				this.vv[i][1]+=this.vv[j][1]; // sum exponents
				this.vv[j][0]="";this.vv[j][1]=""} // nill last term equal
			}
		}
//	alert('collected:'+this.vv)

	for (var i=0;i<this.vv.length;i++){// nill null exponent term
			if(this.vv[i][1]==0){this.vv[i][0]="";this.vv[i][1]=""}
	}
//	ww('collected e nilled:'+this.vv)



	this.vv.sort(); // sort um alphabetically
//	ww('collected e sorted:'+this.vv)

	return this.vv;
}




	// +++++++++++++ multiply(x,y)  returns a string with um multiplied 
UM.multiply=function(x,y){
	var k=0;
	newVett=new Array() // a new array will collect all terms from two strings



	for(var i=0;i<x.vv.length;i++){// loading first element terms
		var a1=new Array();
			a1[0]=x.vv[i][0]  // um name
			a1[1]=x.vv[i][1]  // um exponent
		newVett[i]=a1;
	}
	for(var j=0;j<y.vv.length;j++){// // loading second element terms
		var a2=new Array();
			a2[0]=y.vv[j][0]     // um name
			a2[1]=y.vv[j][1]     // um exponent
		newVett[i+j]=a2;
	}


//	ww('creo prodotto')
//	ww(newVett)
	var prodotto = new UM(newVett);// build & return a new um with data collected
//	ww('pp:',prodotto)
	prodotto.collect();
//	ww('pp2:',prodotto)
	return prodotto;
}





	// ++++++++++++++++ x.divide(y) returns a string with um divided
UM.divide=function(x,y){
//	alert('x='+x)
//	alert('y='+y)
	var k=0;
	newVett=new Array() //vettore che conterr� vettori da due
	for(var i=0;i<x.vv.length;i++){// carico tutti quelli di x
		var a1=new Array();
		a1[0]=x.vv[i][0]
		a1[1]=x.vv[i][1]
		newVett[i]=a1;
	}
//	alert(newVett)




	for(var j=0;j<y.vv.length;j++){// carico tutti quelli di y
		var a2=new Array();
		a2[0]=y.vv[j][0]
		a2[1]=-y.vv[j][1] // being at den power have to be inverted
		newVett[i+j]=a2;
	}
//	alert(newVett)



	var rapporto=new UM(newVett);
//	ww('rapp1='+rapporto)
	rapporto.collect();
//	ww('rapp2='+rapporto)

	return rapporto;
}





// ******************************************************************************
// ******************************************************************************
// ******************************************************************************


// ******************************************************************************
// ******************************************************************************
// ******************************************************************************
// Physical Quantity CLASS  (PQ)
// an element is a vector including a number and a um string  like (8*10^4) m^2 k^3 s^(-1)
// its rappresentatios is:  [8,4,um] ie [ 8, 4 ,  [[_m,2],[_k,3],[_s,-1]] ]



function PQ(_x,_exp,_mis){ //argomenti: x= numero; exp= potenza dieci; _mis um
	this.x=_x;
	this.exp=_exp;
	// POLIMORPHISM: if _mis is a vector:
	if(_mis.length >0 ){
		this.mis=new UM(_mis);
	}
	else{ // if _mis is already a um:
		this.mis=_mis
	}
}

new PQ(0,0,[['dummy',0]])
PQ.precision=3;
PQ.prototype.toString=function (){
	this.mis.collect();
	return (
		trunc(this.x,PQ.precision)+
		( (this.exp==0)? '':'<big><sup>'+dot+'</big></sup>'+'10<sup> '+this.exp+'</sup> '  ) +
		this.mis.toString()+' '
	)
}
PQ.prototype.clone=function(){
	var s="";
	s+=this.x;
	s+=','+this.exp
	var ss="[ "
	var comma=','
	for (var i=0;i<this.mis.vv.length;i++){
		if(i==this.mis.vv.length-1){comma=''}
		ss+= "['" + this.mis.vv[i][0] + "'," + this.mis.vv[i][1] + "]"+comma
	}

	ss+=' ]'
	s+=','+ss
	return s;
}


PQ.multiply=function(x,y){
	return new PQ( x.x*y.x, x.exp+y.exp ,UM.multiply(x.mis,y.mis) );
}



PQ.pow=function(x,n){
//	wwl('inPQ.pow azsx='+azsx)
	return (new PQ( Math.pow(x.x,n), x.exp * n ,UM.pow(x.mis,n))  );
}

PQ.divide=function(x,y){
	return new PQ( x.x/y.x, x.exp-y.exp ,UM.divide(x.mis,y.mis));
}



PQ.sum=function(x,y){
	var z=x.x*Math.pow(10,x.exp)+y.x*Math.pow(10,y.exp)
	return new PQ( z, 0 ,x.mis);
}

PQ.diff=function(x,y){
	var z=x.x*Math.pow(10,x.exp)-y.x*Math.pow(10,y.exp)
	return new PQ( z, 0 ,x.mis);
}



PQ.scalarMultiply=function(x,n){
	var z=(x.x*Math.pow(10,x.exp) ) *n
	return new PQ( z, 0 ,x.mis);
}

PQ.prototype.normalize=function(){
	// Adjust mantissa to x.yyy
	var og=Math.round(log10(this.x));
	this.x/=Math.pow(10,og);
	this.exp=(this.exp*1+og*1)
	return this;
}
//***********************


graph library

// graph library
//   A library to implement graphic on JavaScript by Giovanni Nicco
//   Commands have  Java syntax
//
//
//                                
//   drawArc(x,y,l,h,alpha0,alpha1): draw an arc of oval from alpha0 to alpha1 (radians)
//   drawImage(x,y,fileName) : draws an image (fileName) in x,y 
//   drawOval(x,y,width,heigth): draw an oval (or circle) (use last setColor color)
//   drawLine(x0,y0,x1,y1): draws a line from x0,y0 to x1,y1
//   drawRect(x0,y0,width,heigth): draws a rectangle
//   drawString(s,x,y): draws a strings s in x,y
//   fillArc(x,y,l,h,alpha0,alpha1): draw a filled arc of oval from alpha0 to alpha1 (radians)
//   fillRect(x0,y0,width,heigth,color): draw a filled rectangle (need color)
//   fillOval(x,y,width,heigth): draw a filled oval (or circle) (use last setColor color)
//   setColor(c); sets the color of next figures to be c (unsetted color is black)
//   setPoint(x,y); draw a point in x,y (black or of the color setted by setColor()
var red='red';
var green='green';
var blue='blue';

function drawArc(x,y,l,h,alpha0,alpha1){
		rx=l/2;ry=h/2;
		xc=x+rx;yc=y+ry
		da=Math.PI/360
		for(var alpha=alpha0;alpha<=alpha1;alpha+=da){
			drawLine(xc+rx*Math.cos(alpha),yc-ry*Math.sin(alpha),xc+rx*Math.cos(alpha+da),yc-ry*Math.sin(alpha+da));
		}
}

function drawImage(x,y,i) {
    document.writeln('<SPAN STYLE="position:absolute; left:'+x+'px; top:'+y+'px"><img src="'+i+'"></SPAN>');
}

function drawLine(x0,y0,x1,y1){
	dx=x1-x0;dy=y1-y0;
	if(y1>=y0){versoy=1}else{versoy=-1}
	if(x1>=x0){versox=1}else{versox=-1}
	npx=Math.abs(dx);npy=Math.abs(dy);
	var i=0;
	if( dx*dx >= dy*dy){ // tg <= 45�
		deY=dy/npx;
		with(document){
			while(i++<=npx){
				write('<SPAN STYLE="position:absolute; left:' +x0+ '; top:' +y0+ '">.</SPAN>');
				x0+=versox;y0+=deY
			}
		}
	}
	else{ // tg > 45�
		deX=dx/npy;
		with(document){
			while(i++<=npy){
				write('<SPAN STYLE="position:absolute; left:' +x0+ '; top:' +y0+ '">.</SPAN>');
				y0+=versoy;x0+=deX;
		        }
	        }
         }
}

function drawOval(x,y,l,h){
	rx=l/2;ry=h/2;
	xc=x+rx;yc=y+ry
	da=Math.PI/360
	for(var alpha=0;alpha<=6.29;alpha+=da){
		drawLine(xc+rx*Math.cos(alpha),yc- ry*Math.sin(alpha),xc+rx*Math.cos(alpha+da),yc- ry*Math.sin(alpha+da));
	}
}


function drawRect(x0,y0,l,h){
	x0=Math.floor(x0);y0=Math.floor(y0);
	l=Math.ceil(l);h=Math.ceil(h);
	drawLine(x0,y0,x0+l,y0);
	drawLine(x0,y0,x0,y0+h);
	drawLine(x0+l,y0+h,x0+l,y0);
	drawLine(x0+l,y0+h,x0,y0+h);
}

function drawString(s,x,y){
	document.write('<SPAN STYLE="position:absolute; left:' +x+ 'px; top:' +y+ 'px">'+s+'</SPAN>');
}


function fillArc(x,y,l,h,alpha0,alpha1){
	rx=l/2;ry=h/2;
	xc=x+rx;yc=y+ry
	da=Math.PI/180
	for(var alpha=alpha0;alpha<=alpha1;alpha+=da){
		drawLine(xc,yc,xc+rx*Math.cos(alpha+da),yc-ry*Math.sin(alpha+da));
	}
}


function fillOval(x,y,l,h){
	var rx=l/2; var ry=h/2;
	var xc=x+rx;var yc=y+ry
	for(var xx=x+l;xx>=-x;xx--){
		alpha=Math.acos((xx-x)/l)
		drawLine(xc+rx*Math.cos(alpha),yc-ry*Math.sin(alpha),xc+rx*Math.cos(-alpha),yc-ry*Math.sin(-alpha));
	}
}

function fillRect(x,y,w,h,color){
	document.write(	'<DIV STYLE="position: absolute; top:'+	y+'; left:'+
	x+'; width:'+w+	'; height:'+h+'; background-color: '+	color+' "   ></div>'	)
}





function setColor(c){
	document.write('<font color='+c+'>');
}



function setPoint(x,y){ 
	document.write('  <SPAN STYLE="position:absolute; left:' +x+ 'px; top:' +y+ 'px">.</SPAN> ' );
}






Peter Jipsen library for math rendering

// math rendering

/*
ASCIIMathML.js
==============
This file contains JavaScript functions to convert ASCII math notation
to Presentation MathML. The conversion is done while the (X)HTML page 
loads, and should work with Firefox/Mozilla/Netscape 7+ and Internet 
Explorer 6+MathPlayer (http://www.dessci.com/en/products/mathplayer/).
Just add the next line to your (X)HTML page with this file in the same folder:
<script type="text/javascript" src="ASCIIMathML.js"></script>
This is a convenient and inexpensive solution for authoring MathML.

Version 1.4.7 Aug 7, 2005, (c) Peter Jipsen http://www.chapman.edu/~jipsen
Latest version at http://www.chapman.edu/~jipsen/mathml/ASCIIMathML.js
For changes see http://www.chapman.edu/~jipsen/mathml/asciimathchanges.txt
If you use it on a webpage, please send the URL to jipsen@chapman.edu

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.

This program is distributed in the hope that it will be useful, 
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License (at http://www.gnu.org/copyleft/gpl.html) 
for more details.
*/

var checkForMathML = true;   // check if browser can display MathML
var notifyIfNoMathML = true; // put note at top of page if no MathML capability
var mathcolor = "blue";       // change it to "" (to inherit) or any other color
var mathfontfamily = "serif"; // change to "" to inherit (works in IE) 
                              // or another family (e.g. "arial")
var displaystyle = true;      // puts limits above and below large operators
var showasciiformulaonhover = true; // helps students learn ASCIIMath
var decimalsign = ".";        // change to "," if you like, beware of `(1,2)`!
var AMdelimiter1 = "`", AMescape1 = "\\\\`"; // can use other characters
var AMdelimiter2 = "$", AMescape2 = "\\\\\\$", AMdelimiter2regexp = "\\$";
var doubleblankmathdelimiter = false; // if true,  x+1  is equal to `x+1`
                                      // for IE this works only in <!--   -->
//var separatetokens;// has been removed (email me if this is a problem)
var isIE = document.createElementNS==null;

if (document.getElementById==null