Missing JavaScript Functionality

JavaScript does not offer a lot of things one would imagine would be included in such a seasoned scripting language. Below are a few functions I wrote to fill some gaps.

Trimming the whitespace off both sides of a string

function trim(str) {
return str.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
};

Padding the start of a string

function pad(str, len, padding) {
str += "";

if ( str.length <= len ) {
var str_new = "";
for ( i = 0; i < len – str.length; i++ )
str_new += padding;

return str_new + str;
}

return str;
};

Getting the mouse position

var mouse_x = mouse_y = 0;

function mouse_position_update() {
if ( document.all && !window.opera ) {
mouse_x = event.clientX + document.documentElement.scrollLeft;
mouse_y = event.clientY + document.documentElement.scrollTop;
}
else {
mouse_x = e.pageX;
mouse_y = e.pageY;
}
};

Getting an elements absolute position

function element_position(element) {
var x = y = 0;

if ( element.offsetParent ) {
x = element.offsetLeft;
y = element.offsetTop;
while ( element = element.offsetParent ) {
x += element.offsetLeft;
y += element.offsetTop;
}

return [x, y];
};

All of these were tested in Microsoft Internet Explorer 8, Mozilla FireFox 3.5.8, Google Chrome 5.0.307.9 beta, and Apple Safari 4.0.4.

Please note I have not touched JavaScript in years and I am a bit rusty.

Update 2010.03.02
I noticed an extra bracket in element_position() which is now fixed. Sorry about that.

  1. No comments yet.

  1. No trackbacks yet.