Screencast #1 – Event Delegation in jQuery

Last week Nettuts’ editor Jeffrey posted about a new screencast competition. This isn’t my entry – it’s just a test-runner to see if I’m any good at the whole screencast thing. It’s a 30-minute screencast about event delegation in jQuery and in it I explain event bubbling/propagation and then go on to demonstrate how to develop an event delegation plugin for jQuery.

Note: The quality isn’t too great but if you make it full screen it’s much better!

Thanks for watching, if you have any feedback I’d love to hear it! I’m planning on recording my entry for that competition soon, it’ll also be on jQuery although I’m not sure of the exact topic yet…

Here’s the plugin we created in the screencast:

$.fn.delegate = function(selector, event, action) {
    return this[event.replace(/^on/,'')](function(e){
        var target = e ? e.target : window.event.srcElement,
            elements = $(selector, this),
            elementsLength = elements.length;
 
        elementLoop:
            while (elementsLength--) {
                var parents = $(target).parents(),
                    parentsLength = parents.length;
 
                parentLoop:
                    for (var pi = 0; pi < parentsLength; pi++) {
                        if ( $(parents[pi]).is(selector) ) {
                            return action.call(elements[elementsLength]);
                        }
                    }
 
                if (elements[elementsLength] === target) {
                    return action.call(elements[elementsLength]);
                }
            }
 
        return true; // We don't want to prevent default action so returning true is best
    });
}
 
// USAGE EXAMPLE:
$('ul').delegate('li', 'click', function(){
    $(this).parent().append( $(this).clone() );
});

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!