1. July 2011
von Blackbam

These are my todays top 10 Javascript functions which I gathered in more than 6 months of casually Javascript Development. Almost each of them helped out of more than one problem, so they deserve to be perpetuated here and help again. Most of these are not written by me, but by some other great programmer on the web, and I really would like to mention all of them here if I would know where I have got all of these great scripts.

 

Have fun an use wisely.

1. Get Elements By Class Name (getElementsByClassName)

This is maybe one of the most used and most needed custom Javascript functions of all time. It provides a way to get all elements in a page with a certain class attribute.

function getElementsByClassName(classname, node){
    if (!node) {
        node = document.getElementsByTagName('body')[0];
    }
 
    var a = [], re = new RegExp('\\b' + classname + '\\b');
    els = node.getElementsByTagName('*');
    for (var i = 0, j = els.length; i < j; i++) {
        if (re.test(els[i].className)) {
            a.push(els[i]);
        }
    }
    return a;
}

2. Test if Internet Explorer is used and get its version number

I do not know how much functions, CSS selectors or whatever - IE so often acts different or just stupid. It always requires extra work. This after all will help you to detect this nasty browser.

// use the class
if(Browser.Version() <8) {
	// make crazy IE shit
}
 
var Browser = {
    Version: function(){
        var version = 999; // we assume a sane browser
        if (navigator.appVersion.indexOf("MSIE") != -1) 
            // bah, IE again, lets downgrade version number
            version = parseFloat(navigator.appVersion.split("MSIE")[1]);
        return version;
    }
}

3. Clear input-field onclick, if value is default

This is not much of javascript, we actually call it dynamic html. It is just the standard way to present the comfortable input fields to users.


4. Test if a String is not empty

Can help to avoid a lot of common mistakes with javascript.

var bpat    = /\S/;
function isNonblank (s) {
   return String (s).search (bpat) != -1
}

5. Function Exists

This is a possibility in Javascript to test if a function exists (like function_exists in PHP). This can be useful in cases of debugging or when you are not sure if some required script file is loaded, for example.

if(typeof yourFunctionName == 'function') {
     yourFunctionName();
}

6. Get scroll width/height of page visitors' browser window

A browser-safe way to get the number of pixels, which a user scrolled down the webpage currently.

function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
 
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}

7. Get current size of page visitors' browser window

A browser-safe way to get the window height and window width of the current viewers browser in pixels.

function getWindowSize() {
    var myWidth = 0, myHeight = 0;
 
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [ myWidth, myHeight ];
}

8. Scale images by setting a maximum width/height

It is not always the best idea to scale images with javascript. But I came to several applications there this was useful though.


var images = document.getElementsByTagName("img"); // get your images somehow
scaleImages(imgs,150,150); // call the function
         
// scales the images to a maximum width/height
function scaleImages(images,maxh,maxw) {
  
for(i=0;i ratio){
		// height is the problem
		if (img.height > maxh){
			img.width = Math.round(img.width*(maxh/img.height));
			img.height = maxh;
		}
	} else {
		// width is the problem
		if (img.width > maxh){
			img.height = Math.round(img.height*(maxw/img.width));
			img.width = maxw;
		}
	  }
	  img.setAttribute("class","showpreview ready");
  }
}

9. Print Javascript Array (like print_r()-in PHP)

A really useful function for debugging and developing with javascript. Instead of [object Object] or something similar you will see the whole contents of an array in your output.

	function dump(arr,level) {
		var dumped_text = "";
		if(!level) level = 0;
		
		//The padding given at the beginning of the line.
		var level_padding = "";
		for(var j=0;j \"" + value + "\"\n";
				}
			}
		} else { //Stings/Chars/Numbers etc.
			dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
		}
		return dumped_text;
	}

10. XML2Array (parse xml to javascript array)

For the special case of reading XML with Javascript. But very useful, when it comes to the case. It is much easier to handle a huge array in Javascript than reading lots of data from a complex XML-file. Maybe there is a tiny disadvantage concerning speed, but I think it is worth that.

//////////////////////////////////// xml2array() ////////////////////////////////////////
// See http://www.openjs.com/scripts/xml_parser/
var not_whitespace = new RegExp(/[^\s]/); //This can be given inside the funciton - I made it a global variable to make the scipt a little bit faster.
var parent_count;
//Process the xml data
function xml2array(xmlDoc,parent_count) {
	var arr;
	var parent = "";
	parent_count = parent_count || new Object;

	var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
	*	If 1, Value and Attribute will be shown inside the tag - like this...
	*	For the XML string...
	*	http://www.bin-co.com/
	*	The resulting array will be...
	*	array['guid']['value'] = "http://www.bin-co.com/";
	*	array['guid']['attribute_isPermaLink'] = "true";
	*	
	*	If 0, the value will be inside the tag but the attribute will be outside - like this...	
	*	For the same XML String the resulting array will be...
	*	array['guid'] = "http://www.bin-co.com/";
	*	array['attribute_guid_isPermaLink'] = "true";
	*/

	if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
		if(xmlDoc.childNodes.length > 1) { //If its a parent
			arr = new Object;
			parent = xmlDoc.nodeName;
			
		}
	}
	var value = xmlDoc.nodeValue;
	if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
		if(not_whitespace.test(value)) {//If its a child
			arr = new Object;
			arr[xmlDoc.parentNode.nodeName] = value;
		}
	}

	if(xmlDoc.childNodes.length) {
		if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
			arr = xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
		} else { //If there is more than one childNodes, go thru them one by one and get their results.
			var index = 0;

			for(var i=0; i2) break;//We just need to know wether it is a single value array or not
					}

					if(assoc && arr_count == 1) {
						if(arr[key]) { 	//If another element exists with the same tag name before,
										//		put it in a numeric array.
							//Find out how many time this parent made its appearance
							if(!parent_count || !parent_count[key]) {
								parent_count[key] = 0;

								var temp_arr = arr[key];
								arr[key] = new Object;
								arr[key][0] = temp_arr;
							}
							parent_count[key]++;
							arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
						} else {
							parent_count[key] = 0;
							arr[key] = temp[key];
							if(xmlDoc.childNodes[i].attributes && xmlDoc.childNodes[i].attributes.length) {
								for(var j=0; j
Share

Warning: Undefined variable $time_since in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/single.php on line 42 Dieser Eintrag wurde am 1. July 2011 um 0:00 in der Kategorie JavaScript / Ajax, Web Development veröffentlicht. You can book the comments for this article RSS 2.0. Feedback, discussion, commendation and critics are welcome: Write a comment or trackback.


Tags: , , ,

Fatal error: Uncaught Error: Undefined constant "Ext_related_links" in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/single.php:75 Stack trace: #0 /home/.sites/609/site1266/web/blackbams-blog/wp-includes/template-loader.php(106): include() #1 /home/.sites/609/site1266/web/blackbams-blog/wp-blog-header.php(19): require_once('/home/.sites/60...') #2 /home/.sites/609/site1266/web/blackbams-blog/index.php(17): require('/home/.sites/60...') #3 {main} thrown in /home/.sites/609/site1266/web/blackbams-blog/wp-content/themes/SilentWoodsByBlackbam/single.php on line 75 WordPress › Error

There has been a critical error on this website.

Learn more about troubleshooting WordPress.