JavaScript

Small But Useful Functions. Part 1

Over time I've accumulated a collection of small JavaScript utility functions that I use across many projects. These don't merit their own full posts, but they're worth sharing.

1. Get element by class name (pre-querySelector):

function getElementsByClass(className, tag, parent) {
    parent = parent || document;
    var elements = parent.getElementsByTagName(tag || '*');
    var result = [];
    for (var i = 0; i < elements.length; i++) {
        if ((' ' + elements[i].className + ' ').indexOf(' ' + className + ' ') > -1) {
            result.push(elements[i]);
        }
    }
    return result;
}

2. Add window load event (safe stacking):

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

3. Get absolute position of an element:

function getAbsoluteTop(el) {
    var top = 0;
    while (el) {
        top += el.offsetTop;
        el = el.offsetParent;
    }
    return top;
}

function getAbsoluteLeft(el) {
    var left = 0;
    while (el) {
        left += el.offsetLeft;
        el = el.offsetParent;
    }
    return left;
}

4. Cross-browser event binding:

function addEvent(el, type, fn) {
    if (el.addEventListener) {
        el.addEventListener(type, fn, false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + type, fn);
    }
}

More utility functions coming in Part 2!