Click to See Complete Forum and Search --> : [JS] Useful JS functions

02-27-2007, 09:18 PM
Theres a lot of useful Javascript functions out there, and I bet a lot of users has some too. So, lets start a list with useful functions.

Top 10 custom JavaScript functions of all time (http://www.dustindiaz.com/top-ten-javascript/)

Pluss my own one. This one is useful when you want to get the value out of a css property. Since element.style.height will return "20px", we need to remove the two last characters. It does that, but I also made it so it can remove any number of characters from the beginning or end of a string.

String.prototype._ = function(n){
return this.substring((n<0 ? -n : 0), (n<0 ? this.length : this.length-n))*1;

02-28-2007, 06:12 AM
Nice :) I think that could come in handy, though, I wouldn't use it for working with CSS property values (what if someone had used % for margin top? or if you wanted to get two properties and add them?). I think parseInt should be the way to go for that.

A couple of functions I've found useful - trim leading/trailing whitespace from a string,

// trim leading whitespace from a string
String.prototype.ltrim = function() {
return this.replace(/^\s+/, '');
// trim training whitespace from a string
String.prototype.ttrim = function() {
return this.replace(/\s+$/, '');
// trim both leading and trailing whitespace from a string
String.prototype.trim = function() {
return this.ltrim().ttrim();


var msg = ' hello world ';
alert('-' + msg + '-' + msg.trim() + '-' + msg.ltrim() + '-' + msg.ttrim() + '-');

a hitch like function (or whatever you choose to call it - http://boring.youngpup.net/2005/0525024806/comments has examples of things like this) can also be incredibly useful,

function hitch(obj, fn) {
return function() { fn.apply(obj, arguments); }


// create a class
var SomeClass = function() {};
SomeClass.prototype.toString = function() {
return 'SomeClass';
// add a method that should be used as an event handler
SomeClass.prototype.linkClickHandler = function() {
// create an instance and use hitch to get it to respond to an onclick event
var s = new SomeClass();
document.getElementById('some-link').onclick = hitch(s, s.linkClickHandler);

without the use of hitch. e.g,

document.getElementById('some-link').onclick = s.linkClickHandler;

within s.linkClickHandler "this" would no longer refer to the object s.

02-28-2007, 12:12 PM
I like the trim functions, but what does hitch do?

02-28-2007, 09:35 PM
I built these the other day trying to fix my div height problem. They didn't end up helping but I think they'll come in handy.

This is an attempt to wrangle the window to act more like flash's Stage object.

function setStage(){
if (window.innerWidth){ //Non-IE
this.width = window.innerWidth;
this.height = window.innerHeight;
}else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
this.width = document.documentElement.clientWidth;
this.height = document.documentElement.clientHeight;
}else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
this.width = document.body.clientWidth;
this.height = document.body.clientHeight;

var Stage = new setStage();

This one returns an object with properties that refer to a given id. Found it the other day and haven't tried in all browsers.

function getObj(name){
if (document.getElementById){ //W3C DOM
this.obj = document.getElementById(name);
this.style = document.getElementById(name).style;
}else if (document.all){ //Microsoft DOM
this.obj = document.all[name];
this.style = document.all[name].style;
}else if (document.layers){ //Netscape DOM
this.obj = document.layers[name];
this.style = this.obj;


var j = new getObj('jar');
var s = window.getComputedStyle(j.obj,null).height;

This one attempts to return the value of any property of any id
uses getObj() from above

function getStyle(el,prop){
var s = new getObj(el);
if( window.getComputedStyle ) {
var value = window.getComputedStyle(s.obj,null)[prop];
} else if( s.obj.currentStyle ) {
var value = s.obj.currentStyle[prop];
return value;


var n = getStyle('jar','height');

I'm pretty new to js so these might not be that inclusive and as I've said the cross-browser DOM thing is a joke so I doubt I'll be writing much of my own.

03-01-2007, 06:31 PM
I like the trim functions, but what does hitch do?

Hitch allows you to control the object scope a function is executed in. It's especially useful with Object Oriented Javascript. Consider the following simple class,

ScopeTest = {
prop: 'A property in scope test',
method: function() {

If we then do,


we should see the alert 'A property in scope test' popup.

In Javascript we can also assign functions/methods to variables and then use the variable to call them, like this,

var func = ScopeTest.method; // note no () since we're assigning the method itself to a variable, not calling the method and assigning it's return value
func(); // call ScopeTest.method

This calls our method, but the alert pops up a message saying our property is undefined. This is because by assigning the method to the variable and calling it in this way we've changed the object scope from the ScopeTest object to the window object. that is, within the method 'this' now points to the window object instead of the ScopeTest object. And since window doesn't have a property named 'prop' we find this.prop is undefined.

Using hitch gives control over the object scope. If we used it to assign the method to our variable like this,

var func = hitch(ScopeTest, ScopeTest.method);

We would get the desired result - our alert box would display the property correctly. This is most useful with event handlers. It means we can assign a method of a class to an event handler (say onclick) and keep 'this' within that method pointing at the object it is a method of.

someButton.onclick = ScopeTest.method;

when the click event triggers ScopeTest.method the alert box would show undefined again.

But using hitch,

someButton.onclick = hitch(ScopeTest, ScopeTest.method);

We'd see our message in the alert box when the click event happens.

Hope this helps :)

Oh, I like the setStage function :)

04-22-2007, 12:56 PM
Bumping :p

I made a new function today. This one makes it possible to post mailto links on a webpage without being afraid of spambots. It encrypts the address by shifting each character 23 steps and puts this in the href field.

My email is 82818892922376888641808674828523768886.

The script will encode any email in php and print it as an encrypted mailto link. Only when a visitor clicks the link will it be decoded.

My email will look like this when encrypted:
<a href="mailto:82818892922376888641808674828523768886@turn _on_javascript.com" onclick="email(this);">Click here for my email</a>

This is the php script that encrypts the email:

function encrypt($val){
$num_out = "";
if($val == ""){
return "";
$str_in = urlencode($val);
for($i = 0; $i < strlen($str_in); $i++){
$num_out .= ord(substr($str_in, $i, 1)) - 23;
return "mailto:".urldecode($num_out)."@turn_on_javascript.com";
print('<a herf="'.encrypt($email).'" onclick="email(this)">Click here for my email</a>');

Then you need this javascript on the page:

function email(elm){
var val = elm.href;
val = val.substring(val.indexOf(":")+1, val.indexOf("@"));
var str_out = "";
if(val == ""){
return false;
}else {
var num_out = val;
var num_in = "";
for(var i = 0; i < num_out.length; i += 2) {
num_in = parseInt(num_out.substr(i,[2])) + 23;
num_in = unescape('%' + num_in.toString(16));
str_out += num_in;
elm.href = "mailto:"+str_out;
elm.innerHTML = unescape(str_out);
return true;