Useful code

Superceded!

All of this functionality can be achieved in one convenient package using jQuery.

Add and Remove element classes

Can’t remember where I found this, but its a simple way to add and remove classes dynamically from HTML elements

function removeClass (el, className) {
	if (!(el && el.className)) {
		return;
	}
	var cls = el.className.split(" ");
	var ar = new Array();
	for (var i = cls.length; i > 0;) {
		if (cls[--i] != className) {
			ar[ar.length] = cls[i];
		}
	}
	el.className = ar.join(" ");
}

function addClass (el, className) {
	removeClass(el, className);
	el.className += " " + className;
}

Add OnLoad Handlers

These code snippets from: http://simon.incutio.com/archive/2004/05/26/addLoadEvent

This is the best way to add onload handlers to a page from multiple different scripts and have them all executed.

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

New events can then be added from any JavaScript code using the functions as in these examples:

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* more code to run on page load */ 
});

Change Opacity

function setOpacity(obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;
	if (obj.style.opacity) {
		// CSS3 - Safari 1.2, newer Firefox and Mozilla
		obj.style.opacity = opacity/100;
	} else if (obj.style.filter) {
		// IE/Win
		obj.style.filter = "alpha(opacity:"+opacity+")";
	} else if (obj.style.MozOpacity) {
		// Older Mozilla and Firefox
		obj.style.MozOpacity = opacity/100;
	} else if (obj.style.KHTMLOpacity) {
		// Safari<1.2, Konqueror
		obj.style.KHTMLOpacity = opacity/100;
	} else {
		// opacity not supported
		return false;
	}
}

getElementsByClass

This code snippet from: http://www.dustindiaz.com/getelementsbyclass/

function getElementsByClass(searchClass,tag,node) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

Posted in

One Response to "Useful code"

Leave a reply