Missing JavaScript Functionality

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.

Dump variable contents

function var_dump(arr, level) {
if ( !level )
level = 0;

var dumped_text = “”;
var level_padding = “”;
for ( var j = 0; j < = level; j++ ) level_padding += "\t"; if ( typeof(arr) == "object" ) { for ( var item in arr ) { var value = arr[item]; if ( typeof(value) == "object" ) { dumped_text += level_padding + "\"" + item + "\" =>\n”;
dumped_text += var_dump(value, level + 1);
}
else
dumped_text += level_padding + “\”” + item + “\” => \”” + value + “\”\n”;
}
}
else
dumped_text = “===>” + arr + “< ===(" + typeof(arr) + ")"; return dumped_text; };

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

function mouse_position() {
if ( document.all && !window.opera )
return [event.clientX + document.documentElement.scrollLeft, event.clientY + document.documentElement.scrollTop];

return [e.pageX, 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.

Leave a Reply

Your email address will not be published.