Useful code snippets

Subscribe to Useful code snippets 13 posts, 9 voices

 
dob Scriptwright

Hey,

I was thinking I'd open up a thread where people can post their most useful code snippets, classes, functions etc.

So without further ado,

here's a couple of mine:

function getparam(param) {
	var url = window.location.href;
	url = url.substring(url.lastIndexOf("/"));
	var params = url.split("?")[1];
	if (params.indexOf("&") > 1 &&  params.indexOf(param) > -1) {
		params = params.split("&");
		for (var i=0; i<params.length; i++) {
			if (params[i].indexOf("=") > -1) {
				if (params[i].split("=")[0] == param && params[i].split("=")[1]) {
					return params[i].split("=")[1];
				}
			}
		}
	}
}

I just wrote it. It will return the $_GET value for a URL, for example:

on Domain: http://mydomain.com/file.php?param1=string1&param2=int2, getparam("param1"); will return string1

It's a little buggy, but for me it works fine.

Another one:

String.prototype.trim = function() {
	return this.replace(/^\s*(.*[^\s])?\s*$/, "$1");
}

will trim the given string, for example:

var mystring = "    string  ";
mystring.trim() // returns "string"

Real easy, but quite useful.

And last but not least:

Array.prototype.pop = function() {
	return this[this.length-1];
}

returns the last element of the given array, for example:

var arr = new Array("cat", "dog", "mouse");
alert(arr.pop()) // alerts "mouse"

So, maybe some of you have useful stuff also and would like to share it?
Thanks!

 
Mikado Scriptwright
people can post their most useful code snippets

http://wiki.greasespot.net/Code_snippets

var url = window.location.href; url = url.substring(url.lastIndexOf("/")); var params = url.split("?")[1];

Aka location.search

String.prototype.trim

' test \n string '.trim()

Array.prototype.pop

http://developer.mozilla.org/en/docs/Core_JavaS...

 
Mindeye Scriptwright

A better trim function is:

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}

 
dob Scriptwright

This one doesn't match the spaces in "string ", it needs a whitespace at the beginning.

And Mikado: I just wanted to see what you guys use about every day, simple functions and not huge xpath classes like in the wiki.

 
Mindeye Scriptwright


This one doesn't match the spaces in "string ", it needs a whitespace at the beginning.

The function I posted doesn't need a space at the beginning:
"string ".trim() ---> "string"
" string".trim() ---> "string"
" string ".trim() ---> "string"

And the spaces inside the string aren't removed (" 1 2 ".trim() ---> "1 2"), like it should. A trim function isn't supposed to remove those spaces

 
Joel H Scriptwright

The function I use most:

alert(string);

There's nothing like knowing exactly what a variable contains; need be, a program can be debugged by adding a corresponding alert statement to every line of the code to make sure it's doing what you think it's doing.

-Joel

 
dob Scriptwright

Ever heard of GM_log(string)? Works just fine if you ever forget a break; during a loop, and alert() definitely sucks then.

 
gollum Scriptwright Need to move to the next or previous element and find having to sometimes skip whitespace text nodes. So instead of obj.nextSibling.nextSibling.firstChild you could do nextElement(obj).firstChild

function nextElement(node){if(!node){return null;}do{node=node.nextSibling;}while(node && node.nodeType !=1);return node;}
function prevElement(node){if(!node){return null;}do{node=node.previousSibling;}while(node && node.nodeType !=1);return node;}

Admittedly, these proved most useful when writing x-browser scripts

 
Descriptor Scriptwright

http://developer.mozilla.org/en/docs/DOM:elemen...

http://developer.mozilla.org/en/docs/Whitespace...

 
Joel H Scriptwright

dob:

The gm logger works well, especially for a production script, but when I'm developing I don't want to have to stop and look at the log file when I could just have it jump in my face instead. As for loops, you're right; you just need to be careful.

-Joel

 
jerone Scriptwright

You want useful code's? Check this script out: US_functions and here explained.

 
JoeSimmons Scriptwright

// Add a script to the page to be used globally
function addScript(aS_text) {
var h = document.evaluate("//head",document,null,9,null).singleNodeValue;
if(h && aS_text !== '') {
var aS = document.createElement('script');
aS.type = 'text/JavaScript';
aS.innerHTML = aS_text;
h.appendChild(aS);
return true;
}
else {return false;}
}
// XPath
function xp(_exp, t, n) {
var exp = _exp || "//*"; // XPath Expression
var type = t || 6; // XPath type (e.g., 6=unordered node snapshot)
var node = n || document; // XPath search node (only for advanced users; research it)
if(type==9) {return document.evaluate(exp, node, null, 9, null).singleNodeValue;}
else {return document.evaluate(exp, node, null, type, null);}
}
// Get ID
function id(ID) {
var id=document.getElementById(ID);
if(id) { return id; }
else { return false; }
}
// Toggle
function toggle(toggle_id) {
if(toggle_id) {
if(id(toggle_id).style.display == "none") { id(toggle_id).style.display = ""; }
else { id(toggle_id).style.display = "none"; }
return true;
}
}
// Remove element by id
function removeElemById(e) {
var _e = document.getElementById(e);
if(_e && _e.parentNode) {
_e.parentNode.removeChild(_e);
return true;
}
else {return false;}
}
// Remove element by class
function removeElemByClass(e, Tag) {
var a, i, atg, tag;
tag=Tag||"*";
atg = document.evaluate("//"+tag+"[@class='"+e+"']", document, null, 6, null);
if(atg.snapshotLength) {
for(i=0; i<atg.snapshotLength; i++)
{
a = atg.snapshotItem(i);
if(a.className == e) {a.parentNode.removeChild(a);}
}
return true;
}
}
ID Hider

 
GIJoe Scriptwright

// void show_alert( string message [,int display] ) : Log and display a message
// display: 0=console only / 1=top of document / 2=bottom of document
function show_alert(msg, display) {
  if(arguments.callee.counter) { arguments.callee.counter++; } else { arguments.callee.counter=1; }
  GM_log('('+arguments.callee.counter+') '+msg);
  if(display==1 || display==2) {
    warningelem=document.createElement('div');
    warningelem.setAttribute("style","color:#FFFFFF; background:#FF8000; width:auto; text-align:center; font-size:24px; border: 3px solid #CC0088; margin:2px;");
    warningelem.textContent=msg;
    if(display==1) { document.body.insertBefore(warningelem, document.body.firstChild); }
    else { document.body.appendChild(warningelem); }
  }
}