Managing Javascript Events

Listening

ECMAScript in all browsers but IE

node.addEventListener("click", function() {
    alert("clicked ECMA");
}, false);
            

IE Only (<=8)

node.attachEvent("onclick", function() {
    alert("clicked IE");
});
            

Conclusion? Don't bother...

JS Frameworks to the rescue!

jQuery

$(node).click(function(e) {
    alert("clicked jQ");
});
$(node).bind("custom", {optional: "dataobj"}, function(){});
            

YUI3

var handleClick = function(e, someArg) {
    alert("clicked YUI");
};
Y.on("click", handleClick, node, someArg);
            

Namespacing / Categories

jQuery

$(node).bind("click.category", function(){ alert('clicked'); });

// unbind with e.g.:
$(node).unbind("click.category");
// stackable like css classes
$(node).unbind(".stacked.categories");
            

YUI3

Y.on("category|click", handleClick, node);

// detach all with e.g.:
Y.detach("category|*");
// or...
Y.detach("click", handleClick, node);
            

Dispatching

Plain JS createEvent

var e = document.createEvent('MouseEvents');
e.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

if (node.dispatchEvent(e)) {
    alert("not canceled");
}
            

jQuery

$(node).click();
$(node).trigger("click", [data]);
$(node).triggerHandler("click", [data]);
            

YUI3

Y.one('.selector').simulate("click", {obj: "foo"});
            

Event Phases

Capture

Note: The propagation stops at the event target

Bubbling

Handling

Receiving the event object

function clickHandler(e) {
    // e = event object
}
            

Stopping the event

$('.red .green', slide).click(function (e) {
    // stops the bubbling process to red*
    e.stopPropagation();
    alert('green');
});

$('.red .yellow', slide).click(function (e) {
    alert('yellow');
});

$('.red', slide).click(function (e) {
    // blocks propagation to red2
    e.stopImmediatePropagation();
    alert('red1');
});
$('.red', slide).click(function (e) {
    alert('red2');
});
            
RED
GREEN
YELLOW

Preventing the default behavior

function clickHandler(e) {
    // equivalent to the old-school
    // "return false"
    e.preventDefault();
    alert('blocked..');
}
$('a', slide).click(clickHandler);
            
Test link

What is this?

function clickHandler(e) {
    // e.target = node that triggered the event
    alert('target: '+$(e.target).css('borderColor'));
    // e.currentTarget = node we're listening to
    alert('currentTarget: ' +
        $(e.currentTarget).css('borderColor'));
    // this = e.currentTarget
    alert('this: '+$(this).css('borderColor'));
}
$('.red', slide).click(clickHandler);
            
RED
GREEN

In YUI this is wrapped in a YUI.Node, in jQuery it is a standard DOM Node.

Thank you.

Questions?

References & Links