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!)

javascript value of selected option

// what is the value of the selected option?

this.options[this.selectedIndex].value

Print a PDF file using the Acrobat Pro Javascript Console in OS X

// Print a PDF file using the Acrobat Javascript Console
// Press Command J to bring up the console in Acrobat
// After typing your code in the console, select it and press Control Enter to execute
// Uses current Page Setup when printing

var myDoc;

myDoc = app.openDoc("/Users/yourusername/Desktop/outputfolder/filename.pdf");
myDoc.print({bUI : false});
myDoc.closeDoc();

Mozilla export coordinates to a .kml file (for Google Earth)

Usage:
// define a location hash:
var location = {
    'name':'Tokyo',
    'latitude':35.65444,
    'longitude':139.74472
    // Other data: 
    //'heading' : 0 ,
    //'tilt' : 0 ,
    //'range':  1000000 
}
// choose a name for your .kml file:
var myFileName = 'my_geo.kml';

// now use them to force opening a .kml file:
$google.openKMLFile(location,myFileName);

Will output:
<?xml version="1.0" encoding="UTF-8" ?> 
<kml xmlns="http://earth.google.com/kml/2.0">
<Document>
<Placemark>
<name>Tokyo</name> 
<Point>
<altitudeMode>relativeToGround</altitudeMode> 
<coordinates>139.74472,35.65444,0</coordinates> 
</Point>
<LookAt>
<heading>0</heading> 
<tilt>0</tilt> 
<range>1000000</range> 
<latitude>35.65444</latitude> 
<longitude>139.74472</longitude> 
</LookAt>
</Placemark>
</Document>
</kml>


Helper library :
var $google = { 
	
	_exampleLocation : { 
		'name':'Tokyo',
		'latitude':35.65444,
		'longitude':139.74472
		// Other data: 
		//'heading' : 0 ,
		//'tilt' : 0 ,
		//'range':  1000000 
	},
	
	_CC : Components.classes,
	
	_CI : Components.interfaces,
	
	_getDOMImpl : function(){
		if (this._domImpl == null){
			this._domImpl = this._CC["@mozilla.org/xmlextras/domparser;1"].createInstance(this._CI.nsIDOMParser).parseFromString("<foo/>", "text/xml").implementation;
		}
		return this._domImpl;
	},
	
	_stringToTmpFile: function(dataString, charset, tmpFileName) {
		var unicodeConverter = this._CC["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(this._CI.nsIScriptableUnicodeConverter);
		unicodeConverter.charset = charset;
		var convertedString = unicodeConverter.ConvertFromUnicode(dataString);
				
		var tmpFile = this._CC["@mozilla.org/file/directory_service;1"].getService(this._CI.nsIProperties).get("TmpD", this._CI.nsILocalFile);
									 
		tmpFile.append(tmpFileName);
		tmpFile.createUnique(this._CI.nsIFile.NORMAL_FILE_TYPE, 0664);
	
		var outStream = this._CC["@mozilla.org/network/file-output-stream;1"].createInstance(this._CI.nsIFileOutputStream);

		outStream.init(tmpFile, 0x02 | 0x08 | 0x20, 0664, 0);
		outStream.write(convertedString, convertedString.length);
				
		var finalData = unicodeConverter.Finish();
		if (finalData.length > 0) {
			outStream.write(finalData, finalData.length);
		}
		outStream.close(); 
		
		return tmpFile ; 
	},
	
	openKMLFile : function(location,fileName) {
		
		if (!location || location == '') {  location = this._exampleLocation ; }
			
		var doc = this._getDOMImpl().createDocument("http://earth.google.com/kml/2.0", "kml", null);
				
		var kmlDocument = doc.createElement("Document");
		doc.documentElement.appendChild(kmlDocument);
		
		var kmlPlacemark = doc.createElement("Placemark")
		kmlDocument.appendChild(kmlPlacemark);
		
		var kmlName = doc.createElement("name");
		kmlPlacemark.appendChild(kmlName);	
		
		var kmlPoint = doc.createElement("Point");
		kmlPlacemark.appendChild(kmlPoint);

		var kmlAltitudeMode = doc.createElement("altitudeMode");
		kmlPoint.appendChild(kmlAltitudeMode);
		
		var kmlCoordinates = doc.createElement("coordinates");
		kmlPoint.appendChild(kmlCoordinates);
		
		var kmlLookAt = doc.createElement("LookAt");
		kmlPlacemark.appendChild(kmlLookAt);

		var kmlHeading = doc.createElement("heading");
		kmlLookAt.appendChild(kmlHeading);

		var kmlTilt = doc.createElement("tilt");
		kmlLookAt.appendChild(kmlTilt);
		
		var kmlRange = doc.createElement("range");
		kmlLookAt.appendChild(kmlRange);
		
		var kmlLatitude = doc.createElement("latitude");
		kmlLookAt.appendChild(kmlLatitude);
		
		var kmlLongitude = doc.createElement("longitude");
		kmlLookAt.appendChild(kmlLongitude);
	
		kmlName.appendChild(doc.createTextNode(location.name));
		kmlAltitudeMode.appendChild(doc.createTextNode("relativeToGround"));
		kmlCoordinates.appendChild(doc.createTextNode(location.longitude + "," + location.latitude + ",0"));	
		kmlHeading.appendChild(doc.createTextNode(location.heading ? location.heading : '0'));
		kmlTilt.appendChild(doc.createTextNode(location.tilt ? location.tilt : '0'));
		kmlRange.appendChild(doc.createTextNode(location.range ? location.range : '1000000'));
		kmlLatitude.appendChild(doc.createTextNode(location.latitude));
		kmlLongitude.appendChild(doc.createTextNode(location.longitude));		
		
		var serializer = this._CC["@mozilla.org/xmlextras/xmlserializer;1"].createInstance(this._CI.nsIDOMSerializer);
		var kmlString = '<?xml version="1.0" encoding="UTF-8"?>' + serializer.serializeToString(doc);

		var kmlFile = this._stringToTmpFile(kmlString, "UTF-8", fileName);
		kmlFile.launch();
		
	}
	
}

Round.. when there is no round

I needed a math.round in Javascript, there was none available in my environment... a new japanese phone
function Round(number){
	newnumber=number*10;
	remainder=newnumber%10;
	newnumber-=remainder;
	if(remainder>5){
		newnumber+=10;
	}
	newnumber=newnumber/10;
	if(newnumber%1!=0){
		newnumber=Round(newnumber*10)/10
	}
	return newnumber;
}

ie. alert (Round(66.3523)) should give 66

xpath helper function

function $xpath(q,doc) { if (!doc || doc == '') {doc = document ; } return doc.evaluate(q, doc,null,XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,null); }

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);

Resize image to fit container

Resizes an image to fit into its container, depending on whether the width or height is longer, yet keeping the aspect ratio. Copied from a comment on sitepoint.com.

ffunction resizeImgOO(el) 
{ 
	function imgRatio()
	{ 
		return (el.height / el.width); 
	} 
	function holderRatio()
	{ 
		return (el.offsetParent.offsetHeight / el.offsetParent.offsetWidth); 
	} 
	function fitToContainer()
	{ 
		if(imgRatio>holderRatio) 
		{ 
			el.height = el.offsetParent.offsetHeight; 
		} 
		else 
		{ 
			el.width = el.offsetParent.offsetWidth;	
		} 
	}
	
	this.imgRatio = imgRatio; 
	this.holderRatio = holderRatio; 
	this.resize = fitToContainer; 
}
var img = new resizeImgOO(document.getElementById('yourImgId'));
img.resize();

Walk Google Maps Dom and pick out image tiles

// Elliot wrote this to grab google maps image tiles.

  m = document.getElementById("map_canvas");
      gold = m.childNodes[0].childNodes[0].childNodes[1];
      list = gold.getElementsByTagName('img');
      a = new Array(list.length);
      for (var i = 0; i < list.length; i++)
      {
        a[i] = list[i].getAttribute('src');
      }
      alert(data);