javascript delegate custom click event

function addEvent(elem, event, func) {
    if (elem.addEventListener) {
        elem.addEventListener(event, func, false);
    } else if (elem.attachEvent) {
        elem.attachEvent('on' + event, func);
    } else {
        elem['on' + event] = func;
    }
}

function customHandler(e) {
    var src, parts;
    // get event and source element
    e = e || window.event;
    src = e.target || e.srcElement;

    if (src.nodeName.toLowerCase() !== "button") {
        return;
    }

    // actual work: update label
    parts = src.innerHTML.split(": ");
    parts[1] = parseInt(parts[1], 10) + 1;
    src.innerHTML = parts[0] + ": " + parts[1];

    // no bubble
    if (typeof e.stopPropagation === "function") {
        e.stopPropagation();
    }
    if (typeof e.cancelBubble !== "undefined") {
        e.cancelBubble = true;
    }
    // prevent default action
    if (typeof e.preventDefault === "function") {
        e.preventDefault();
    }
    if (typeof e.returnValue !== "undefined") {
        e.returnValue = false;
    }
}

var target = document.getElementById('click-wrap');
addEvent(target, 'click', customHandler);

html:

<div id="click-wrap">
    <button>Click me: 0</button>
    <button>Click me too: 0</button>
    <button>Click me three: 0</button>
</div>

Leave a Comment