Sunday, January 8, 2012

Frequently used Javascript function

Frequently used function fragment, include:
check whether a dom element has a css class
insert dom element before another dom element
remove child dom element
get vertical scrollbar width of a div
trim left and right space of a string
replace all '.'
substring
get event in a function
get target from event
get elements by class name
Remove element from array by index

check whether a dom element has a css class

domElement.className.match(new RegExp('(\\s|^)'+the_class_name+'(\\s|$)'));

insert dom element before another dom element

anotherDom.parentNode.insertBefore(newDom, anotherDom);


remove child dom element

parent.removeChild(child)


get vertical scrollbar width of a div
div.offsetWidth - div.clientWidth;


trim left and right space of a string


string.replace(/^\s\s*/, '').replace(/\s\s*$/, '');

replace all '.'

string.replace(/\./g,'').replace(/,/g,'');

substring

// include start and exclude end
// e.g., '12345'.substring(2, 4)
//        result is 34
string.substring(start, end);


get event in a function


element.onmouseover = function (event) {
 if (!event) // IE will not pass event
  event = window.event;
}

get target from event


// srcElement is for IE
var target = (event.currentTarget) ? event.currentTarget : event.srcElement;

get elements by class name


// get elements by class name with respect to specific element
function getElementsByClassName (clsnm, parent) {
 var result = [];
 if (!parent)
  parent = document;
 // IE do not have getElementsByClassName
 if (parent.getElementsByClassName)
  result = parent.getElementsByClassName(clsnm);
 else {
  var tmp = parent.getElementsByTagName('*');
  for (var i = tmp.length-1; i >= 0; i--)
   if (tmp[i].className && tmp[i].className.match(new RegExp('(\\s|^)'+clsnm+'(\\s|$)')))
    result.push(tmp[i]);
 }
 return result;
}

Remove element from array by index

// splice (startIndex, length)
// remove 'length' elements from startIndex
// length = 1 -> remove one element
theArray.splice(idx, 1);


References
http://snipplr.com/view/3561/addclass-removeclass-hasclass/
http://blog.stevenlevithan.com/archives/faster-trim-javascript
http://stackoverflow.com/questions/960419/javascript-ie-event
http://stackoverflow.com/questions/857439/internet-explorer-and-javascript-event-currenttarget

No comments:

Post a Comment